loop with struct fields and plot (changing plot styles) - matlab - matlab

that's a thing that is making me a bit crazy-noob so far.
I have my struct storing data from successive experiments, 7 field per each experiment:
veq1
rpmdispl1
displ1
tau1
sigma1
mu1
v_displ1
veq2
...
Then i'd like to plot in for loops, like (k is total datasets to be plotted)
figure(1)
hold all
for ii=1:k;
subplot(2,1,1)
eval(['plot(struct.displ',num2str(ii),',struct.tau',num2str(ii),')']);
subplot(2,1,2)
eval(['plot(struct.displ',num2str(ii),',struct.v_displ',num2str(ii),')']);
end
But actually I am not allowed in changing plot axes style among the plots of the loop. (using either roots or gca settings, line and color string variables, etc)
So i thought to do it in a different way, like:
for ii=1:k;
subplot(2,1,1)
plot(struct.displ(num2str(ii)),struct.tau(num2str(ii)),line,color)
subplot(2,1,2)
plot(struct.displ(num2str(ii)),struct.v_displ(num2str(ii)),line,color);
end
But no way. This last is only an idea (rather than a working code), I admit it. Can somebody suggest me something to work it out?
I'd be grateful.

Related

How do I plot inside a for loop? Matlab

I'm trying to plot a straight line from a point in x to different values of t, thereby making a line in a for loop. But I see no lines generated in my figure in MATLAB
Following is my code:
t=linspace(0,8,11)
xs=(1.+t).^0.5
x0=xs./(1.+t)
m=size(t)
n=max(m)
hold on
for k=1:n
plot(x0(k),t(1:k),'-')
hold on
end
Thanks
You do not need the loop to perform the plot.
plot(x0,t,'-')
Will work just fine! Unless you were attempting to plot points...use scatter() for that:
scatter(x0,t)
plot() and scatter() (and most of Matlab's functions) are meant to be used with vectors, which can take some time to get used to if you are used to traditional programming languages. Just as you didn't need a loop to create the vector x0, you don't need a loop to use plot().
You are adding one point in Y axis along a line in X Axis use this code
t=linspace(0,8,11)
xs=(1.+t).^0.5
x0=xs./(1.+t)
m=size(t)
n=max(m)
hold on
for k=1:n
plot(x0(1:k),t(1:k),'-')
hold on
end
for more fun and see exactly how for is performed use this for loop
for k=1:n
pause('on')
plot(x0(1:k),t(1:k),'-')
hold on
pause(2)
end

Matlab, figures and for loops

I am trying to plot the following simple function; $y=A.*x$ with different A parameter values i.e. A=0,1,2,3 all on the same figure. I know how to plot simple functions i.e. $y=x$ by setting up x as a linspace vector so defining x=linspace(0,10,100); and I know that one can use the hold command.
I thought that one could simply use a for loop, but the problem then is getting a plot of all the permutations on one figure, i.e. I want a plot of y=t,2*t,3*t,4*t on the same figure. My attempt is as follows:
x=linspace(0,10,100);
%Simple example
Y=x;
figure;
plot(Y);
%Extension
B=3;
F=B*x;
figure;
plot(F);
%Attempt a for loop
for A= [0,1,2,3]
G=A*x;
end
figure;
plot(G);
This is how I would plot your for loop example:
figure;
hold all;
for A=[0,1,2,3]
G=A*x;
plot(G);
end
figure creates a new figure. hold all means that subsequent plots will appear on the same figure (hold all will use different colours for each plot as opposed to hold on). Then we plot each iteration of G within the loop.
You can also do it without the loop. As with most things in Matlab, removing the loop should give improved performance.
figure;
A=[0,1,2,3];
G=x'*A;
plot(G);
G is the outer product of the two vectors x and A (with x having been transposed into a column vector). plot is used to plot the columns of the 100x4 matrix G.

For loop in matlab plot

Hello i am having some problems understading basic plotting in matlab.
I can understand why you would use a for loop when plotting data?
Can anybody explain this to me?
I am making a simple linear plot. Is there any reason this should be inside a loop
If you are making a simple plot there is virtually no reason to use a loop.
If you check doc plot you will find that plot can take some vectors as input, or even matrices for more interesting situations.
Example:
x=0:0.01:1;
y=sin(x);
plot(x,y)
No there is no need in Matlab to use a for loop for plotting. If you are looking for a simple linear plot your code could look like this:
x=1:100;
y=3*x+4;
plot(x,y)
As you see there is no for loop needed. Same goes for nearly all plots and visualization.
A possible reason to use a for loop to plot thing may be having several data to plot in a single matrix. Say you have two matrix Ax (MxN) and Ay (MxN) where N the length of each data and M is the amount of different data wanted to plot. For example like in this case N is 201 and M is 3:
% Create Ax and Ay
Ax=meshgrid(0:0.1:20,1:3);
Ay=zeros(size(Ax));
% Sinusoidals with different frequencies
for k=1:3
Ay(k,:)=sin(k.*Ax(k,:));
end
% create colours
colorVec = hsv(3);
% Plot
hold on
for k=1:3
plot(Ax(k,:),Ay(k,:),'Color',colorVec(k,:))
end
hold off
You get:

Write Equation from Fit in Legend, Matlab

So, I've fitted an exponential curve to some data points using 'fit' and now I want to get the equation of the fitted curve in the Legend in the graph. How can I do that? I want to have an equation on the form y=Ce^-xt in the legend. Can I get the coefficients, C and x from the fitted curve and then put the equation inside the legend? Or can I get the whole equation written out in some way? I have many plotted graphs so I would be grateful if the method is not so much time consuming.
Edit: Perhaps I was unclear. The main problem is how I should get out the coefficients from the fitted line I've plotted. Then I want to have the equation inside the legend in my graph. Do I have to take out the coefficients by hand (and how can it be done?) or can Matlab write it straight out like in, for example, excel?
The documentation explains that you can obtain the coefficients derived from a fit executed as c = fit(...), as
coef=coeffvalues(c)
C=coef(1)
x=coef(2)
You can create your own legend as illustrated by the following example.
Defining C and x as the parameters from your fits,
% simulate and plot some data
t= [0:0.1:1];
C = 0.9;
x = 1;
figure, hold on
plot(t,C*exp(-x*t)+ 0.1*randn(1,length(t)),'ok', 'MarkerFaceColor','k')
plot(t,C*exp(-x*t),':k')
axis([-.1 1.2 0 1.2])
% here we add the "legend"
line([0.62 0.7],[1 1],'Linestyle',':','color','k')
text(0.6,1,[ ' ' num2str(C,'%.2f'),' exp(-' num2str(x,'%.2f') ' t) ' ],'EdgeColor','k')
set(gca,'box','on')
Example output:
You may have to adjust number formatting and the size of the text box to suit your needs.
Here is a piece of code that will display the fitted equation in the legend box. You can reduce the amount of digits in the legend by manipulating the sprintf option: %f to %3.2f for example.
%some data
load census
s = fitoptions('Method','NonlinearLeastSquares','Lower',[0,0],'Upper',[Inf,max(cdate)],'Startpoint',[1 1]);
f = fittype('a*(x-b)^n','problem','n','options',s);
%fit, plot and legend
[c2,gof2] = fit(cdate,pop,f,'problem',2)
plot(c2,'m');
legend(sprintf('%f * (x - %f)^%d',c2.a,c2.b,c2.n));
The command disp(c2) will display in the command window what is stored in the fit object. Also, by enabling the "datatip in edit mode" option (Matlab preferences, then Editor, then Display), you will have an instant view on the data stored by putting your mouse cursor over an object.
function [S]=evaFit(ffit)
S=sprintf('y=%s',formula(ffit));
S2='';
N=coeffnames(ffit);
V=coeffvalues(ffit);
for i= 1:numcoeffs(ffit)
S2=sprintf('%s %c=%f',S2, string(N(i)), V(i));
end
S=sprintf('%s%s',S, S2);
end

MATLAB scatter3, plot3 speed discrepencies

This is about how MATLAB can take very different times to plot the same thing — and why.
I generate 10000 points in 3D space:
X = rand(10000, 1);
Y = rand(10000, 1);
Z = rand(10000, 1);
I then used one of four different methods to plot this, to create a plot like so:
I closed all figures and cleared the workspace between each run to try to ensure fairness.
Bulk plotting using scatter3:
>> tic; scatter3(X, Y, Z); drawnow; toc
Elapsed time is 0.815450 seconds.
Individual plotting using scatter3:
>> tic; hold on;
for i = 1:10000
scatter3(X(i), Y(i), Z(i), 'b');
end
hold off; drawnow; toc
Elapsed time is 51.469547 seconds.
Bulk plotting using plot3:
>> tic; plot3(X, Y, Z, 'o'); drawnow; toc
Elapsed time is 0.153480 seconds.
Individual plotting using plot3:
>> tic; hold on
for i = 1:10000
plot3(X(i), Y(i), Z(i), 'o');
end
drawnow; toc
Elapsed time is 5.854662 seconds.
What is it that MATLAB does behind the scenes in the 'longer' routines to take so long? What are the advantages and disadvantages of using each method?
Edit:
Thanks to advice from Ben Voigt (see answers), I have included drawnow commands in the timing — but this has made little difference to the times.
The main difference between the time required to run scatter3 and plot3 comes from the fact that plot3 is compiled, while scatter3 is interpreted (as you'll see when you edit the functions). If scatter3 was compiled as well, the speed difference would be small.
The main difference between the time required to plot in a loop versus plotting in one go is that you add the handle to the plot as a child to the axes (have a look at the output of get(gca,'Children')), and you're thus growing a complicated array inside a loop, which we all know to be slow. Furthermore, you're calling several functions often instead of just once and incur thus calls from the function overhead.
Recalculation of axes limits aren't an issue here. If you run
for i = 1:10000
plot3(X(i), Y(i), Z(i), 'o');
drawnow;
end
which forces Matlab to update the figure at every iteration (and which is A LOT slower), you'll see that the axes limits don't change at all (since the default axes limits are 0 and 1). However, even if the axes limits started out differently, it wouldn't take many iterations for them to converge with these data. Compare with omitting the hold on, which makes plotting take longer, because axes are recalculated at every step.
Why have these different functions? scatter3 allows you to plot points with different marker sizes, and colors under a single handle, while you'd need a loop and get a handle for each point using plot3, which is not only costly in terms of speed, but also in terms of memory. However, if you need to interact with different points (or groups of points) individually - maybe you want to add a separate legend entry for each, maybe you want to be able to turn them on and off separately etc - using plot3 in a loop may be the best (though slow) solution.
For a faster approach, consider this third option (directly uses the low-level function LINE):
line([X,X], [Y,Y], [Z,Z], 'LineStyle','none', 'Marker','o', 'Color','b')
view(3)
Here are some articles discussing plotting performance issues:
Performance: scatter vs. line
Plot performance
Well, if you wanted control over the color of each point, bulk scatter would be faster, because you'd need to call plot separately.
Also, I'm not sure your timing information is accurate because you haven't called drawnow, so the actual drawing could take place after toc.
In summary:
plot3 is fastest because it draws the same marker at many different locations
scatter3 draws many different markers, since size and color of the marker (are allowed to) vary with each point
calling in a loop is really slow, because argument parsing and so forth have to take place repeatedly, in addition as points are added to the plot the axes have to be recalculated