Fitting a curve using matlab - matlab

I have a plot with two intersecting parabolas. Is there a way that I can detect the two correctly and fit two parabolas, one through each of them? My current code fits only a single parabola:
x=-100:1:100;
y=(x.^2)/(4);
x1=-50:1:150;
y1=(x.^2)/(4);
x=[x,x1];
y=[y,y1];
f = fittype('((x)*(x))/4*p',...
'dependent',{'y'},'independent',{'x'},...
'coefficients',{'p'})
fit1= fit(x',y',f)
plot(fit1,x,y)

Following the suggestions I was able to write a code that runs ransac for curves
function [f1] = Ransac(x,y)
voting=[0,0,0,0];
for i=1:10000
[y1,idx] = datasample(y,5);
x1=x(idx);
p = polyfit(x1,y1,2);
f1 = polyval(p,x);
error=(((f1-y).^2));
error(error>100)=0;
indx =find(ismember(voting(:,1:3),'rows'),1);
if (isempty(indx)==1)
voting=[voting;[p,sum(error)]];
else
voting(indx,4) = voting(indx,4)+sum(error);
end
end
[s,t]=max(voting(:,4));
p=voting(t,1:3);
f1 = polyval(p,x);
end

Related

Matlab Plotting with Labels

I'm trying to plot a knn result from my data, which has 3 columns: x, y , label. There are 3 classes and for each of them I would like to used a different symbol. Here's the way I'm plotting now:
t1 = data(:,3) == 1;
t2 = data(:,3) == 2;
t3 = data(:,3) == 3;
train1 = data(t1,:);
train2 = data(t2,:);
train3 = data(t3,:);
figure(1);
plot(train1(:,1),train1(:,2),'#',train2(:,1),train2(:,2),'*',train3(:,1),train3(:,2),'o');
I want to know if there's a more concise way of doing this. Thanks
Here's the most concise (and working) way to plot your data:
figure(1);
hold all
plot(train1(:,1),train1(:,2),'o')
plot(train2(:,1),train2(:,2),'x')
plot(train3(:,1),train3(:,2),'s')
Here's an example that does what you want in a robust and modular manner. You can easily add classes or modify the figure output.
data = [0.53,0.17,2;0.78,0.60,3;0.93,0.26,1;0.13,0.65,2;0.57,0.69,1;...
0.47,0.75,3;0.010,0.45,1;0.34,0.080,3;0.16,0.23,3;0.79,0.91,3;...
0.31,0.15,1;0.53,0.83,2];
categories = [1,2,3];
symbols = {'s','<','o','d','v','+','x','*'};
figure;
hold all
for loopj = 1:length(categories)
t = data(:,3) == categories(loopj);
train = data(t,:);
label = strcat('Class ',num2str(categories(loopj)));
plot(train(:,1),train(:,2),symbols{loopj},'DisplayName',label,'LineWidth',1.3)
end
lg = legend('show');
lg.Location = 'best';
Use hold all to write on the figure without erasing the previous axi and let Matlab pick line colors.
In any case, you need to manually define the different symbols and each plot command comes with one unique type of line and markers.

Matlab: Working for-loop breaks in parfor while fitting curves

Hoping you may be able to assist me with this error. I am running some code to fit curves to ages using a cross validation regime. I iterate the curve fitting 1000 times to assess the best fit.
I define my models as:
linear_ft = fittype({'x', '1'});
monotonic_ft= fittype({'-1/x', '1'});
quadratic_ft = fittype('poly2');
I then run the following to iterate through different selections of data splitting, recording the residuals following the curve fit...
Data = randn(4,300,10,10);
Ages = randn(300,1);
for thisDim1 = 1:4
for thisDim2 = 1:10
for thisDim3 = 1:10
for nIts = 1:1000
RandomOrder = randperm(300,300);
Fit_Subs = RandomOrder(1:length(Ages)/2); % Take random subs to fit to
Test_Subs = RandomOrder(length(Ages)/2+1:300); % Take random subs to test fit to
Fit_Data = squeeze(Data(thisDim1,Fit_Subs,thisDim2,thisDim3)); % Take data to fit to
Test_Data = squeeze(Data(thisDim1,Test_Subs,thisDim2,thisDim3)); % Take data to test fit
Fit_Ages = Ages;
Fit_Ages(Fit_Subs) = []; %Take ages of Fit Subs only
Test_Ages = Ages;
Test_Ages(Test_Subs) = []; % Take ages of Test Subs only
Nsubs = (length(Ages)/2);
% Model Data using Curves
fFit_Lin = fit(Fit_Ages,Fit_Data',linear_ft);
fFit_Mon = fit(Fit_Ages,Fit_Data',monotonic_ft);
fFit_Quad = fit(Fit_Ages,Fit_Data',quadratic_ft);
% Fit Modelled Data to Test Data
tFit_Lin = fFit_Lin(Test_Ages);
tFit_Mon = fFit_Mon(Test_Ages);
tFit_Quad = fFit_Quad(Test_Ages);
% Calculate Median Residual
Lin_Med_Resid(nIts) = median(tFit_Lin - Test_Data');
Mon_Med_Resid(nIts) = median(tFit_Mon - Test_Data');
Quad_Med_Resid(nIts) = median(tFit_Quad - Test_Data');
end
end
end
end
If you run this with the fourth loop (nIts) as a for-loop it will run. If you run it as a parfor-loop it won't stating the error:
Error using fit>iFit (line 264)
The name 'lower' is not an accessible property for an instance of class
'llsqoptions'.
Error in fit (line 108) [fitobj, goodness, output, convmsg] = iFit(
xdatain, ydatain, fittypeobj, ...
Does anyone have any idea how to fix this? I would be most grateful for any advice!!
Thanks,
Ben
Try restarting MATLAB or typing clear all to see if it clears things up for you.
Your code works for me, but the parallel toolbox can be a bit finicky in my experience.

How to label graph edges with a loop?

I'm using a for loop to add more nodes and edges on my plot. However, when I add labels on new edges the old labels are removed. I don't know how to keep old edge-labels nor how to store the results of labeledge.
This is what I have got so far.
for r = 1: 10
for j = 1:10
H = addnode(P,nodeName{r}{j});
P = addedge(H, s{r}{j}, t{r}{j}, w{r}{j});
figure;
hold on;
h = plot(P);
labeledge(h,s{r}{j},t{r}{j},labelText{r}{j})
end
end
Every time in the new plot, I can only see the newest cluster of labels while old labels are gone. Ideally, I'd love to hold on the results of labeledge but hold on can't do this. I need to show labels in each step in the loop, thus adding another overall labeledge is not my ideal solution. Any hint would be appreciated.
Edit: All my variables are multiple cells of difference sizes in cell arrays. I use for loop to help to pick up vectors from cells because I don't know how to insert all the levels of information from such cell arrays of cells etc. into addNode function.
The main problem in your code is that you keep plotting the graph again and again. This isn't necessary. Instead, use one loop to create the graph object (G), then plot it all at once, and then use another loop for labeling the graph:
P = graph;
for r = 1: 10
for j = 1:10
P = addedge(P, s{r}{j}, t{r}{j}, w{r}{j});
end
end
h = plot(P);
for r = 1: 10
for j = 1:10
labeledge(h,s{r}{j},t{r}{j},labelText{r}{j})
end
end
If you wish to plot your graph on every iteration, you can use subgraph for that:
for k = 1:height(P.Nodes)
H = subgraph(P,1:k);
figure;
h = plot(H);
c = 1;
out = false;
for r = 1: 10
if ~out
for j = 1:10
if c < k
labeledge(h,c,labelText{r}{j})
else
out = true;
break
end
c = c+1;
end
else
break
end
end
end
Besides that, you should know that (from Matlab documentation):
For the best performance, construct graphs all at once using a single call to graph. Adding nodes or edges in a loop can be slow for large graphs.
Also, regardless of the above recommendation, for an easier manipulation of your data, you should first convert your cells to an array. If your cell array contains a different number of elements in each cell, then it is better to collapse it all to one column:
C = [s{:}]; % and the same for t and w
while any(cellfun(#iscell,C))
C = vertcat(C{:});
end
C = cellfun(#(x) x(:),C,'UniformOutput', false);
S = vertcat(C{:});
Labels = [labelText{:}]; % and the same nodeName
while any(cellfun(#iscell,Labels))
Labels = vertcat(Labels{:});
end
Try to remove the 'figure;' command out of the FOR loop and try to see if this worked.

avoide loop for dot product, matlab

I have two vectors and I want to get their dor product without for loop. It would save a lot of time.
Here is sample code.
p=1;
C=zeros(100,1);
r_a_= rand(1,3);
r_b= rand(100,3);
for it=1:size(r_b,1)
C(p,1) = dot(r_a_,r_b(it,:)) ;
p=p+1
end
To avoide for loop and to call dot function only once, I thought like this
r_a=repmat(r_a_,100,1);
C = dot(r_a,r_b) %%%%%%%% But obviously it gives wrong answer
Any idea?
You can do it with a matrix multiply, like so:
r_a_ = rand(1,3);
r_b = rand(100,3);
C = r_a_ * r_b.'

How to implement similar statements in matlab using a loop?

Look at the code snippet here in the mathworks documentation,
Digital Servo Control of a Hard-Disk Drive
Gf1 = tf(w1*[a1 b1*w1],[1 2*z1*w1 w1^2]); % first resonance
Gf2 = tf(w2*[a2 b2*w2],[1 2*z2*w2 w2^2]); % second resonance
Gf3 = tf(w3*[a3 b3*w3],[1 2*z3*w3 w3^2]); % third resonance
Gf4 = tf(w4*[a4 b4*w4],[1 2*z4*w4 w4^2]); % fourth resonance
my question is, how can I implement the above statements within a loop like,
% pseudo code
for i = 1:4
Gf%d = tf(w%d*[a%d b%d*w%d],[1 2*z%d*w%d w%d^2]); i
and then execute the result in matlab?
Here's one option:
w = [w1 w2 w3 w4];
%# same thing for a, b, d...
for i=1:4
Gf(i) = tf(w(i)*[a(i) b(i)*w(i)],[1 2*z(i)*w(i) w(i)^2]); % ith resonance
end
You could either use eval:
for i = 1:4
eval(sprintf('Gf%d = tf(w%d*[a%d b%d*w%d],[1 2*z%d*w%d w%d^2]);', i));
end
or you could turn your parameters into arrays. Arrays would be more efficient, if you have control over how you format your data.
The best way to do this is to use arrays.
for i = 1:n
trans(i) = % your stuff here %
end
Then just replace the different variables with the correct array indexes.