Menu
  • HOME
  • TAGS

thicken an object of image to a curve in matlab

matlab,image-processing

This is called "skeletonization" and you can do it with the function bwmorph: bwmorph(Img, 'skel', Inf); Best...

Computing time complexity of the sparse matrix (2)

r,matlab,matrix,sparse-matrix

For every (i, j) pair (there are n^2 in total), you reach the inner part of the loop where you find the similarity and then conditionally add elements to your sparse matrix. Finding the similarity takes "d" operations (because you need to loop through each of your dimensions) and conditionally...

function wait to execute

matlab,events,delay

The "weird behavior and lag" you see is almost always a result of callbacks interrupting each other's execution, and repeated unnecessary executions of the same callbacks piling up. To avoid this, you can typically set the Interruptible property of the control/component to 'off' instead of the default 'on', and set...

MATLAB: How to make camera light follow 3D Rotation

matlab,user-interface,3d,rotation,lighting

Implement own rotation functionality You can implement an own functionality to adjust the axes and the lights at the same time. This way the light gets adjusted continuously while rotating the axes. function follow_me_1 figure axes('buttondownfcn', @buttondownfcn); % assign callback set(gca,'NextPlot','add'); % add next plot to current axis surf(peaks,'hittest','off'); %...

Why do I have a decimal error when writing data to MS Access via Matlab?

matlab,ms-access,rounding,numeric

Rounding a trailing 0 (zero) is not rounding. What you miss is the format that displays the number. Where you do this, set number of decimals to two....

how to calculate probability for each class for predicate with knn without fitcknn?

matlab

First, you have to know that fitcknn & ClassificationKNN.fit will end up with the same result. The difference is that fitcknn is a more recent version, so it allows more options. As an example, if you use load fisheriris; X = meas; Y = species; Then this code will work...

Plot multiple functions on one figure

matlab,matlab-figure

I think you are missing the x limit. xlim([0 2.5*a]) ...

Creating a cell array of workspace variables without manually writing them all out. MATLAB

matlab

Not the fastest way, but you could do it as follows: Saving the desired variables in a temporary file Loading that file to get all those variables in a struct array Converting that struct array to a cell array That is, save temp_file -regexp data\d+ %// step 1 allData =...

Detecting if ranges overlap - MATLAB

matlab

Would it suffice to change the 3rd line of your script to if start(i+1)<max(finish(1:i)) Using your second set of example data, I get the following output: 2900-2996: Tandem 5010-5789: Divergent 6126-7604: Convergent This is what you wanted? Balle...

MATLAB - How to change “Validation Check” count

matlab,neural-network

TL;DL: net.trainParam.max_fail = 8; I've used the example provided in the page you linked to get a working instance of nntraintool. When you open nntraintool.m you see a small piece of documentation that says (among else): % net.<a href="matlab:doc nnproperty.net_trainParam">trainParam</a>.<a href="matlab:doc nnparam.showWindow">showWindow</a> = false; This hinted that some properties are...

How to export fitted curve to 1D vector

matlab

The saved MATLAB-object (default name is fittedmodel) contains the fitted function as a function-handle and the fitted coefficients corresponding to this function-handle. You can then evaluate at the data points of your choice with feval. In the following example the fitted function will be evaluated at the original datapoints x:...

two dimensional unique values in Matlab

arrays,matlab

See docs for unique. Assuming widths and heights are column vectors, [C,ia,ic] = unique([widths, heights],'rows') In contrary, if widths and heights are row vectors, [C,ia,ic] = unique([widths; heights].','rows') ...

free() and mxFree() in MATLAB - freeing memory twice

matlab,memory-management,free,mex

The second loop does not index correctly for tau. You are defining indexing for tau as #define tau(a, b) tau[b+a*NrSensor] Let us walk through the second loop assuming NrSensor = 10 and len_zr = 5. For this case max value of loop variable i is 9 and max value of...

Insert elements to the matrix using index

arrays,matlab

Here's a sort-based approach: array_out = [array_in newElements]; %// append new to old [~, ind] = sort([1:numel(array_in) index-.5]); %// determine new order needed array_out = array_out(ind); %// apply that order ...

Randomly select Elements of 4D matrix in Matlab

matlab,matrix,random,4d

If I am interpreting what you want correctly, for each unique 3D position in this matrix of 7 x 4 x 24, you want to be sure that we randomly sample from one out of the 10 stacks that share the same 3D spatial position. What I would recommend you...

Fastest way to copy some rows from one matrix to another in OpenCV

c++,matlab,opencv,matrix

So I tried different methods for this problem and the only way I could achieve a better performance than Matlab was using memcpy and directly copying the data myself. Mat out( index.cols, w2c.cols, w2c.type() ); for ( int i=0;i<index.cols;++i ){ int ind = index.at<int>(i)-1; const float *src = w2c.ptr<float> (ind);...

Stein-haff shrinkage formula in MATLAB

matlab

The simplest way is to iterate through your values in a for loop adding them to an accumulator variable. The twist in this case - excluding the entries where i==j - would be to use an if statement. innersum = 0; % initialise it first for j = 1:p if...

Why black surf from this Matlab command?

matlab,time-frequency

My bet is that trf is a very large matrix. In these cases, the surface has so many edges (coloured black by default) that they completely clutter the image, and you don't see the surface patches One solution for that is to remove the edges: surf(trf, 'edgecolor', 'none'). Example: with...

Matlab: Using a Variable in Address of Loading

matlab

The documentation: http://www.mathworks.com/help/matlab/ref/load.html, shows that you can supply a string to load by doing: load(filename) where filename is a string. In your case, you can do: load(['sourceETA/Record1/result',num2str(n),'.txt']) ...

Representing bars with different colors in matlab

matlab,bar-chart

Is this what you are looking for? x = [0.22,0.34,0.42]; h = figure; a = axes('parent', h); hold(a, 'on') colors = {'r', 'b', 'g'}; somenames = {'IND Relation'; 'DIS Relation'; 'EQ Relation'}; for i = 1:numel(x) b = bar(i, x(i), 0.1, 'stacked', 'parent', a, 'facecolor', colors{i}); end a.XTick = 1:3;...

solve symbolic system of equations inside an array

matlab,system,equation

Generally this is done (if the eq is in the format you have) with an Ax=b system. Let me show you how to do it with a simple example of 2 eq with 2 unknowns. 3*l1-4*l2=3 5*l1 -3*l2=-4 You can build the system as: x (unknowns) will be a unknowns...

Reading all the files in sequence in MATLAB

matlab,image-processing

From the Matlab forums, the dir command output sorting is not specified, but it seems to be purely alphabetical order (with purely I mean that it does not take into account sorter filenames first). Therefore, you would have to manually sort the names. The following code is taken from this...

Matlab Calculating mean of distribution quantile in a for-loop

matlab,loops,for-loop,distribution,quantile

Your test variable is a three-dimensional variable, so when you do test2 = test(:,1); and then test2(:) <VaR_Calib_EVT/100 it's not the same as in your second example when you do test(:,i)<(VaR_Calib_EVT(:,i)/100) To replicate the results of your first example you could explicitly do the test2 assignment inside the loop, which...

Sum of n-1 columns of a double matrix in MATLAB

matlab,matrix

You can do that by using the function cumsum: A = [1 2 3 4 5 6]; C = cumsum(A); out = [0 C(1:end-1)] now out is: [0 1 3 6 10 15]...

Adding data in intervals in Matlab

matlab

Yes by combining histc() and accumarray(): F =[1.0000 1.0000;... 2.0000 1.0000;... 3.0000 1.0000;... 3.1416 9.0000;... 4.0000 1.0000;... 5.0000 1.0000;... 6.0000 1.0000;... 6.2832 9.0000;... 7.0000 1.0000;... 8.0000 1.0000;... 9.0000 1.0000;... 9.4248 9.0000;... 10.0000 1.0000]; range=1:0.5:10; [~,bin]=histc(F(:,1),range); result= [range.' accumarray(bin,F(:,2),[])] If you run the code keep in mind that I changed the...

Is there a shortcut key to comment multiple lines in matlab editor

matlab,editor

The comment shortcut is CTRL+R on Windows and CTRL+/ on Unix systems (not sure about OS X). To comment multiple lines you'd have to highlight them using the mouse or SHIFT. In any case this can be customized via Preferences -> Keyboard -> Shortcuts....

Create mask from bwtraceboundary in Matlab

image,matlab,image-processing,mask,boundary

It's very simple. I actually wouldn't use the code above and use the image processing toolbox instead. There's a built-in function to remove any white pixels that touch the border of the image. Use the imclearborder function. The function will return a new binary image where any pixels that were...

How to normalise polynomial coefficients in a fraction?

matlab,polynomial-math

You can extract the numerator and denominator with numden, then get their coefficiens with coeffs, normalize the polynomials, and divide again. [n,d] = numden(T); cn = coeffs(n); cd = coeffs(d); T = (n/cn(end))/(d/cd(end)); The output of latex(T) (note: no simplifyFraction now; it would undo things): Of course this isn't equal...

Join matrices with same values in different vectors in MATLAB

matlab,matrix,merge

You don't need to use a loop, use intersect instead. [~,ic,ip] = intersect(c(:, 1:3),p(:, 1:3),'rows'); m = [c(ic, :), p(ip,end)]; Edit: If you want to include NaNs where they don't intersect like the above poster. function m = merge(c, p, nc, np) %check for input arg errors if nargin ==...

Matlab - Multiply specific entries by a scalar in multidimensional matrix

matlab,matrix,multidimensional-array,scalar

Errr, why you multiply indexes instead of values? I tried this: comDatabe(:,:,[1 2 3],:,8) = comDatabe(:,:,[1 2 3],:,8)*-1 And it worked....

MATLAB. Overlay plotted lines onto an existing .avi movie

matlab,avi

Here is a way to do it. The code is commented. I created a dummy movie but if you have one you can skip the first few steps, as indicated. The trick is to use hold on and drawnow to refresh the display correctly. You can add more lines or...

Matrix naming on loop

matlab,octave

Using assignin, you can write a variable to the workspace with a custom name. for i=1:matrices_to_generate matrix = rand(2,2); assignin('base', strcat('matrix', num2str(i)), matrix); end; ...

Matlab: For loop with window array

arrays,matlab,math,for-loop,while-loop

In the meanSum line, you should write A(k:k+2^n-1) You want to access the elements ranging from k to k+2^n-1. Therefore you have to provide the range to the selection operation. A few suggestions: Use a search engine or a knowlegde base to gather information on the error message you received....

How to return an array with unhappy numbers removed?

matlab,function

I've written a small function (which might be further improved) to test the "happines" of a number. Current version only works with scalar and one dim. array. Input: the scalar or array to be tested Output: 1) an index: happy (1) unhappy(0) 2) the list of happy number within the...

Animate through multiple 2D Matlab plots

matlab,plot

I assume with "2d-line" you mean a 2d-plot. This is done by the plot-function, so there is no need of surf or mesh. Sorry, when I got you wrong. The following code does what I think you asked for: % Generate some propagating wave n = 20; t = linspace(0,10,100);...

Matlab: Looping through an array

matlab,loops,for-loop,while-loop,do-while

You could do this using conv without loops avg_2 = mean([A(1:end-1);A(2:end)]) avg_4 = conv(A,ones(1,4)/4,'valid') avg_8 = conv(A,ones(1,8)/8,'valid') Output for the sample Input: avg_2 = 0.8445 5.9715 -0.6205 -3.5505 2.5530 6.9475 10.6100 12.5635 6.4600 avg_4 = 0.1120 1.2105 0.9662 1.6985 6.5815 9.7555 8.5350 avg_8 = 3.3467 5.4830 4.7506 Finding Standard Deviation...

Generate random binary sequence with a specific ratio

arrays,matlab,random

The ratio can be interpreted as deterministic (you want 500 ones and 500 zeros in each realization of 1000 values) or as probabilistic (a realization may have more ones than zeros, but the ratio holds over a very large number of realizations). Your code works for the probabilistic interpretation, so...

Getting time frequency of number in array in Python?

python,arrays,matlab,numpy

I think it is easiest to first think about this in terms of statistics. What I think you are really saying is that you want to calculate the 100*(1-m/nth) percentile, that is the number such that the value is below it 1-m/nth of the time, where m is your sampling...

Matlab: What are the ways to determine the distribution of the data

matlab,statistics,distribution

If I understand correctly, you are asking how to decide which distribution to choose once you have a few fits. There are three major metrics (IMO) for measuring "goodness-of-fit": Chi-Squared Kolmogrov-Smirnov Anderson-Darling Which to choose depends on a large number of factors; you can randomly pick one or read the...

Summing rows at a fixed distance in Matlab?

matlab

In increasing order of generality: If the second column is always cyclical: reshape and sum: result = sum(reshape(A(:,1), m, []), 2); If the second column consists of integers: use accumarray: result = accumarray(A(:,2), A(:,1)); In the most general case, you need unique before accumarray: [~, ~, u] = unique(A(:,2)); result...

how to detect partial corrupted images in Jpg/Jpeg format

matlab,image-processing

I used already detected corrupted images for analyzing corrupted parts. Then use these results to detect possible corruption. Here is Matlab code: clear; clc; FOLDER1 = './'; query_folder1 = FOLDER1; % Some corrupted samples are here. query_pt1 = dir(strcat(query_folder1, '*.jpg')); nFile1 = length(query_pt1); % file number OFF = 10; for...

How to solve for matrix in Matlab?

matlab,matrix,least-squares

Rewrite the quantity to minimise as ||Xa - b||^2 = (definition of the Frobenius norm) Tr{(Xa - b) (Xa - b)'} = (expand matrix-product expression) Tr{Xaa'X' - ba'X' - Xab' + bb'} = (linearity of the trace operator) Tr{Xaa'X'} - Tr{ba'X'} - Tr{Xab'} + Tr{bb'} = (trace of transpose of...

Matlab Distribution Sampling

matlab,distribution,sampling,random-sample

So, you can use this, for example: y = 0.8 + rand*0.4; this will generate random number between 0.8 and 1.2. because rand creates uniform distribution I believe that rand*0.4 creates the same ;) ...

Double integration using experimental data

matlab,data,integration,splines

First of all, you should not use the same letter for a bunch of things; your code is pretty hard to read because one has to figure out what T means at every instance. Second, pure math helps: after a change of variables and simple computation, the double integral becomes...

Display a table in MATLAB

matlab,formatting

I think you just have to transpose them. clc clear angle = (0:1:85)'; polyvals = ((1:86).^2)'; T = table(angle, polyvals) gives T = angle polyvals _____ ________ 0 1 1 4 2 9 3 16 4 25 5 36 6 49 7 64 ...

Matlab Crahes upon fopen in Mex File

c,matlab,fopen,mex

Use w+ or r+ when using fopen, depending on what you want to do with the file and whethe you want to create it or simply open it. From (http://www.tutorialspoint.com/c_standard_library/c_function_fopen.htm) "r" Opens a file for reading. The file must exist. "w" Creates an empty file for writing. If a file...

Read data only when it is present

matlab,data,serial-port,fscanf

Read only when data present You can read out the BytesAvailable-property of the serial object s to know how many bytes are in the buffer ready to be read: bytes = get(s,'BytesAvailable'); % using getter-function bytes = s.BytesAvailable; % using object-oriented-addressing Then you can check the value of bytes to...

Matlab - object orientated with abstract Interface - How creating object?

matlab,object

It is not clear what you want to do exactly and why you need an abstract class then a derived one, but assuming you really need all that for more purpose than you described, take the following into account: By definition in OOP, an abstract class cannot be instantiated. It...

Inserting One Row Each Time in a Sequence from Matrix into Another Matrix After Every nth Row in Matlab

arrays,matlab,matrix

Here's another indexing-based approach: n = 10; C = [A; B]; [~, ind] = sort([1:size(A,1) n*(1:size(B,1))+.5]); C = C(ind,:); ...

Looking for a way to plot angle and distance on a semi circle (MATLAB)

matlab

I think this might do what you want. Just convert to Cartesian and separate into cell arrays. %Generate sample data theta = pi*rand(10, 1); r = 15*rand(size(theta)); %Make (x,y) coordinates x0 = r.*cos(theta); y0 = r.*sin(theta); %Convert to cell arrays, this is assuming a column vector, if it were a...

Connecting two binary objects in matlab

matlab,image-processing

Morphological operations are suitable but i would suggest line structuring element as your arrangement is horizontal and you do not want overlaps between lines: clear clc close all BW = im2bw(imread('Silhouette.png')); BW = imclearborder(BW); se = strel('line',10,0); dilateddBW = imdilate(BW,se); img= imerode(BW,se); figure; imshow(img) ...

Plotting random signal on circle

matlab,plot,signals,circle

You need to add "noise" to the radius of the circle, roughly around r=1: th = linspace( 0, 2*pi, N ); %// N samples noise = rand( 1, N ) * .1; %// random noise in range [0..0.1] r = 1+noise; %// add noise to r=1 figure; plot( r.*cos(th), r.*sin(th)...

Passing parameters to a Matlab function

matlab

From the documentation above, I don't know which one is the right, but there are two common ways for optional parameters in matlab. parameter value pairs: model = oasis(data, class_labels, 'do_sym',1,'do_psd',0) structs: params.do_sym=1 params.do_psd=0 model = oasis(data, class_labels, params) Probably one of these two possibilities is right....

what does ellipsis mean in a Matlab function's argument list?

matlab

http://www.mathworks.com/help/matlab/matlab_prog/continue-long-statements-on-multiple-lines.html Continue Long Statements on Multiple Lines This example shows how to continue a statement to the next line using ellipsis (...). s = 1 - 1/2 + 1/3 - 1/4 + 1/5 ... - 1/6 + 1/7 - 1/8 + 1/9; ...

How to concatenate 3 histograms on the same graph in Matlab

matlab,image-processing,plot,histogram

Assuming uint8 precision, each call to imhist will give you a 256 x 1 vector, and so you can concatenate these together into a single 768 x 1 vector. After, call bar with the histc flag. Assuming you have your image stored in im, do this: red = imhist(im(:,:,1)); green...

Matlab — SVM — All Majority Class Predictions with Same Score and AUC = .50

matlab,svm,auc

Unless you have some implementation bug (test your code with synthetic, well separated data), the problem might lay in the class imbalance. This can be solved by adjusting the missclassification cost (See this discussion in CV). I'd use the cost parameter of fitcsvm to increase the missclassification cost of the...

Visually midway between two points on a x axis log scale [closed]

matlab,math

a=1e-2 b=1e-1 midway = exp((log(a)+log(b))/2) Take the log to get the positions in log scale, then do the math. You could simplify that formula and you will end up with a geometric mean: midway=sqrt(a*b) ...

Import java package from Matlab deploytool to Android Studio App

java,android,image,matlab,jar

Java components that are generated from MATLAB code using deploytool (or using other functionality from MATLAB deployment products such as MATLAB Compiler, MATLAB Builder etc.) depend on the MATLAB Compiler Runtime (MCR). The MCR has much too large a footprint to run on an Android device, and it's really not...

MATLAB Access Classreg

matlab

You can read the file using: >> open classreg.regr.modelutils.tstats This will open "tstats.m". The path of that file on your drive can be a acccessed using: >> which classreg.regr.modelutils.tstats In this folder there are all the other m-files which belong to this class....

using statset for changing the properties in matlab

matlab,factor-analysis

Calling statset with an output argument (as you do at the start of your question) gives you a structure of Statistics Toolbox options that you can pass in to functions such as factoran. If you display the structure, you'll see that it always contains a field for each of the...

Matlab: Writing to a file

arrays,matlab,loops,math,for-loop

If you want to get the matrices to be displayed in each column, that's going to be ugly. If I'm interpreting your request correctly, you are concatenating row vectors so that they appear as a single row. That's gonna look pretty bad. What I would suggest you do is split...

Can I use two separate ODE call functions for a system of two differential equations in MatLab?

matlab,ode

Yes, that's quite possible. Define x as [c;ce], then you have something like: function dx = my_ode(t,x) % parameters definition kf = ...; % whatever value you are using P0 = ...; % whatever value you are using Jer = ...; % whatever value you are using J_serca = ...;...

Matlab: Input Directly a Matrix into a Cell from an Address

matlab

Why do you have a space between load and first parentheses? Try removing the space: Response(1,1)={load(['sourceETA/Tn',num2str(period*10),'/ETdisp.txt'])}; ...

Can we add a statement in between MATLAB codes?

matlab

You need to comment those statements like this r(:,1) = a(:,1) ... % this is a constant - a(:,2); % this is a variable for more information read this ...

K-Means Clustering a list of US addresses based on drive time

excel,matlab,cluster-analysis,k-means,geo

I think you are looking for "path planning" rather than clustering. The traveling salesman problem comes to mind If you want to use clustering to find the individual regions you should find the coordinates for each location with respect to some global frame. One example would be using Latitude and...

Matlab creating mat files which names are written in the variable

matlab

You might have a loop going through the "b"cellarray containing the "filenames" and: 1)get the filename by converting the content of the i-th to a string by using "char" function 2)call "save" specifying the filename (see previous point) and the list of scalar you want to save in it (in...

Shift Plot Data Along X Axis Matlab

matlab,plot,axis,shift

In Matlab, you can plot something using plot(xArray, yArray);. If you want to shift the plot along the x axis, you could use plot(xArray + amountToShift, yArray);. As I believe shifting is not what your real problem is, I've added an example where data gets plotted in the way you...

MATLAB, extracting and saving values in a vector between 0 and 5, then 5 and 10, and so on

matlab

The straightforward approach is to wrap your code into a for loop, something like this: maxValue = 180; data = randperm(maxValue); %//some dummy data binSize = 5; numBins = maxValue / binSize; ranges = cell(1, numBins); for i = 1:numBins ranges{i} = data(binSize * (i - 1) <= data &...

Logic of this FWHM script?

matlab

The two segments of code you specifically mention are both housekeeping: it's more about the compsci of it than the optics. So the first line y = y/max(y); is normalising it to 1, i.e. dividing the whole series through by the maximum value. This is a fairly common practice and...

How to force my output data in a inputdlg on Matlab be a double?

matlab,typeconverter

inputdlg returns a cell array of strings. You can convert to double with str2double: units = str2double(inputdlg(question, title)); ...

Constrained high order polynomial regression

matlab,regression

I would recommend a fourier regression, rather than polynomial regression, i.e. rho = a0 + a1 * cos(theta) + a2 * cos(2*theta) + a3 * cos(3*theta) + ... b1 * sin(theta) + b2 * sin(2*theta) + b3 * sin(3*theta) + ... for example, given the following points >> plot(x, y,...

complexity of generating a sparse matrix

r,matlab,matrix,sparse-matrix

When converting from a full representation of a symmetric matrix to a sparse representation, you will need to scan all the elements on the main diagonal and above (or symmetrically on the main diagonal and below). For an (n x n) matrix matrix this is (n^2+n)/2 entries that need to...

How to create structure in MATLAB with many repeated substructures in an efficient way?

matlab,data-structures

Here is one idea to create the Left field. You could try to adapt it to create the other fields as well: myStruct.Left = cell2struct(repmat({repmat(struct('x', [], 'y', [], 'z', []), 3, 1)}, 18, 1), num2cell('A':'R'), 1); ...

Putting space between bars using bar function

matlab,plot,bar-chart

See the docs for bar. You can reshape info to 2xN (instead of its current shape 1x2N) and then use a single bar command to plot the 2 series, and it will take care of the spacing. See this image from the docs: If you want to keep doing it...

Indicate name of filled areas inside area plot - Matlab?

matlab,matlab-figure

Here is an alternative using annotation objects and the textarrow option, which displays text along with an arrow. This could be useful to you to point in narrow regions where text would hide data. For example: clear clc close all x = 1:128; %// Plot data figure hAxes1 = axes('Position',[.1...

How to access variables in the properties block of a Matlab System Object?

matlab,simulink

You should be able to use properties s = 100; d = zeros(1,100); end right? If you already have the 100 as a default for s, you should also be able to provide this as part of the default for d. I'm guessing that you're trying to avoid doing that...

A function to calculate cumulative maximum for a double matrix in MATLAB

matlab,function,matrix,max

If cummax isn't working then I came up with this little function function m = cummax2(x) [X, ~] = meshgrid(x, ones(size(x))); %replace elements above diagonal with -inf X(logical(triu(ones(size(X)),1))) = -inf; %get cumulative maximum m = reshape(max(X'), size(x)); end ...

How to prevent exceeding matrix dimensions while dividing an image into blocks?

image,matlab,image-processing,image-segmentation

If you simply want to ignore the columns/rows that lie outside full sub-blocks, you just subtract the width/height of the sub-block from the corresponding loop ranges: overlap = 4 blockWidth = 8; blockHeight = 8; count = 1; for i = 1:overlap:size(img,1) - blockHeight + 1 for j = 1:overlap:size(img,2)...

Operating a C++ class from Matlab without mex [closed]

c++,matlab

You can use calllib to call functions in shared library. This would be the newlib.h #ifdef __cplusplus extern "C"{ #endif void *init(int device); #ifdef __cplusplus } #endif and this would be the newlib.cpp file #include "newlib.h" #include "yourlib.h" A *p; extern "C" void *init(int device) { p = new A;...

What is the right way to add function handles recursive and see the right output after printing it?

matlab

You can use the symbolic functions (symfun) to do what you want: % create symbolic variable syms x % define order of polynom n = 3; % create polynom fs(x) = 0*x; for i = 1:n fs(x) = fs(x) + x.^i; end % convert symbolic function to function handle f...

Skip data files while reading input and writing output in matlab code

matlab

you can also test existence of the file using exist n=202; for idx = 0:n infilename = sprintf('pt%d.txt',idx); outname = sprintf('out%d.txt',idx); if exist( infilename , 'file') == 2 do your stuff end end ...

Does Matlab support function-objects?

matlab,function-object

Matlab does have function handles which can be passed to other functions. As one example, the function fzero will find the zero-crossing of the function you give as its first argument. Function handles can be stored in variables, cell-arrays or structs. Matlab also has anonymous functions, which are similar to...

MATLAB removing rows which has duplicates in sequence

arrays,matlab,matrix

So you want to remove rows of A that contain at least t zeros in sequence. How about a single line? B = A(~any(conv2(1,ones(1,t),2*A-1,'valid')==-t, 2),:); How this works: Transform A to bipolar form (2*A-1) Convolve each row with a sequence of t ones (conv2(...)) Keep only rows for which the...

summing matrix columns based on another matrix

matlab

The following should solve the problem, although there's a nicer way to do it using logical indexing (I think) but I can't recall it off the top of my head: for t = 1 : int_ccy; wgts(t,:) = sum(weight .* (country_code == ccy(t, 1)), 1); end ...

How to switch Matlab plot tick labels to scientific form?

matlab,plot

You can change the XTickLabels property using your own format: set(gca,'XTickLabels',sprintfc('1e%i',0:numel(xt)-1)) where sprintfc is an undocumented function creating cell arrays filled with custom strings and xt is the XTick you have fetched from the current axis in order to know how many of them there are. Example with dummy data:...

How to get varargout to output text from pushbuttons in Matlab GUI?

matlab,matlab-guide

I have the answer to my question. A summary of changes: Added uiresume (after adding uiwait in the Opening function) after each Callback Deleted close (gcf) after each Callback; if the figure closes, then hObject and handles in guidata are no longer accessible to the Output function Created a handle...

Properly using button/checkbox callback

matlab,matlab-guide

You have a couple alternatives here. Be aware that callbacks expect 2 input arguments by default so your problem most likely comes from that. I can't find the reference I once saw about this, but you might want to try one of these: 1) In your callback, manually retrieve the...

Trying to draw lines from the origin to coordinates in 2D (MATLAB)

matlab

As noted in the comments, this is fairly easy to do: N = numel(X); Xlines = zeros(2*N,1); Ylines = zeros(2*N,1); Xlines(1:2:end) = X(:); Ylines(1:2:end) = Y(:); plot(Xlines, Ylines, '-'); This constructs the vectors Xlines and Ylines by interleaving them with the point (0,0), which looks exactly like what you want....

Why can't I calculate CostFunction J

matlab,machine-learning

As suggested in the comments, the error is because x is of dimension 3x2 and theta of dimension 1x2, so you can't do X*theta. I suspect you want: theta = [0;1]; % note the ; instead of , % theta is now of dimension 2x1 % X*theta is now a...

xcorr function with impulse response

matlab,filtering,convolution

The following code implements only a part of what I can see in the description. It generates the noise processes and does what is described in the first part. The autocorrelation is not calculated with the filter coefficients but with the actual signal. % generate noise process y y =...

imread function doesn't work in matlab

matlab,image-processing,matlab-figure

The problem you are experiencing comes from saving the data to a MATLAB data file, renaming the file with a .jpg extension and trying to use imread to read in the data. This unfortunately doesn't work. You can't change the file type of your data from .mat to .jpg. All...