Reputation: 699
I was wondering:
Assume I have a structure:
s(1).Xval=[1 2 3];
s(2).Xval=[1 2 3 4];
s(3).Xval=[1 2 3];
s(1).Yval=[1 2 3];
s(2).Yval=[4 3 2 1];
s(3).Yval=[3 2 1];
Now I want to plot these three lines in one plot. I can do this by:
plot(s(1).Xval,s(1).Yval,s(2).Xval,s(2).Yval,s(3).Xval,s(3).Yval);
This is possible because MATLAB offers the opportunity for a variable number of input arguments of the plot function, by means of the syntax:
plot(X1,Y1,...,Xn,Yn)
My question is: is there a way to call this function without a predefined number of plots? So in this case, I plotted three lines, but in case i do not know upfront how many lines I want to plot, is this syntax still possible?
I am of course aware that I could do this by using Hold All
and a For
loop. However, I ask this because I would like to avoid a loop if neccesary. Is there an elegant solution for this? Or should I just resort to using a loop?
Edit: There was indeed a typo with the indexes. s.Xval(1) instead of s(1).Xval
Upvotes: 2
Views: 1543
Reputation: 699
I actually found another method which is to my mind fairly nice.
plotdata = cell(length(s)*2,1);
plotdata(1:2:end) = {s.Xval};
plotdata(2:2:end) = {s.Yval};
plot(axes,plotdata{:});
This code is straightforward and easy to read, and discards the need of a loop.
Upvotes: 1
Reputation: 14108
I assume you have a typo, so the correct struct is this:
s(1).Xval=[1 2 3];
s(2).Xval=[1 2 3 4];
s(3).Xval=[1 2 3];
s(1).Yval=[1 2 3];
s(2).Yval=[4 3 2 1];
s(3).Yval=[3 2 1];
% collect all data into one cell
c = {};
for k = 1 : length(s)
c = cat(2, c, {s(k).Xval}, {s(k).Yval});
end
% and plot:
plot(c{:});
Note, that c{:}
is not a single variable, but as number of elements of c
Update: without the loop, but ugly
c = reshape(reshape({s.Xval, s.Yval}, length(s), [])', [], 1);
plot(c{:});
Upvotes: 1
Reputation: 3640
You can do that with plot function. Documentation mentions that:
If Xn or Yn are matrices, they must be 2-D and the same size, and the columns of Yn are plotted against the columns of Xn. plot automatically chooses colors and line styles in the order specified by ColorOrder and LineStyleOrder properties of current axes.
To make X and Y matrices, you will need to pad them with NaNs. Like this:
X = [1 2 3 NaN
1 2 3 4
1 2 3 NaN]
Y = [1 2 3 NaN
4 3 2 1
3 2 1 NaN]
Since plot function plots column against column, and you want row againts row, you will need to transpose them.
plot(X',Y','Marker','x')
will give you
Upvotes: 3