David
David

Reputation: 77

plot a curve for each parameter in a figure by recalling mat file

I am doing something similar to the following example:

t=linspace(0,1);
z=rand(1);
theta=pi*rand(1);
a_range=[1,2,3];
for nplot=1:3
   a=a_range(nplot);

    x=z*t.^2+a*sin(theta);

end

fname=['xsin.mat'];
save(fname)

the parameter a has three different values. For each value of a, I want to plot the function in one single figure. So at the end I will have three figures. I can do it using subplot but this will generate three plots in one figure which is not what I want.

In a new script, I load the mat file:

load('xsin.mat')

for nplot=1:3

figure(nplot)
plot(t,x)
end

but I get one figure not three as I should have. I mean for a=1, I should plot the curve in figure 1; for a=2, I should plot the curve in figure 2 and so on. How can I do this? Any help is appreciated.

Upvotes: 0

Views: 71

Answers (1)

Thales
Thales

Reputation: 605

You are overwriting x in every iteration; you could modify your code by saving each x for the respective nplot in a separate column of a matrix X (with minimal changes to your code):

t=linspace(0,1);
z=rand(1);
theta=pi*rand(1);
a_range=[1,2,3];

X = NaN(length(t), length(a_range));  % Create matrix to hold x values

for nplot=1:3
   a = a_range(nplot);
   x = z * t.^2 + a * sin(theta);
   X(:,nplot) = x;  % Store x in column of X
end

fname=['xsin.mat'];
save(fname)

Then, to create the figures:

load('xsin.mat')

for nplot=1:3
   x = X(:,nplot);  % Retrieve x from column of X
   figure(nplot)
   plot(t,x)
end

Upvotes: 1

Related Questions