Graph With Variable Number of Plots

조회 수: 2 (최근 30일)
Stephen
Stephen 2012년 11월 14일
I'm writing a piece of code that needs to split up a vector into smaller vectors which are not uniform in length. These smaller vectors then need to be plotted (against another set of smaller vectors which have undergone the same process). I've wrote a loop which gives each smaller vector a similar name using the eval and num2str expressions.
This works to the point that it'll allow me to splot my big vector up and gives me an unlimited number of smaller vectors, each with their own name. However I have a problem when I come to plot them; I don't know how many smaller vectors I will have until I run the code as the places they get cut will depend on initial conditions.
If I use the following code as an very crude example;
for B=1:8
eval(['M' num2str(B) ' = [2 3].^B' ])
eval(['N' num2str(B) ' = [2 4].*B' ])
end
plot(M1,N1,'k',M2,N2,'k',M3,N3,'k',M4,N4,'k',M5,N5,'k',M6,N6,'k', ...
M7,N7,'k',M8,N8,'k')
The above simulates how my code sets the cut up vectors as dynamic names which I can then plot later. Although this code doesn't do it those vectors are of unknown length and number (before I run the code). For example in my actual code M4 and N4 may be twice as long as M5 and N5, and it may only go up to M3 and N3.
Is there any way anyone can think of that my plot code can automatically change how many things are being plotted depending on initial conditions? So for example, in the above case if I changed the value of B to 3 the code would automatically only plot M1 against N1, M2 against N2 and M3 against M3.
The only thing I can think of is a for loop and multiple plot commands but that's far for ideal.
Any help would be appretiated and if there's any questions I'm happy to provide more information.
UPDATE:
An new example where the size of the vectors is not constant
for B=1:8
eval(['M' num2str(B) ' = rand(1,B)' ])
eval(['N' num2str(B) ' = rand(1,B)' ])
end
plot(M1,N1,'b',M2,N2,'b',M3,N3,'b',M4,N4,'b',M5,N5,'b',M6,N6,'b', ...
M7,N7,'b',M8,N8,'b')

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2012년 11월 14일
편집: Azzi Abdelmalek 2012년 11월 14일
hold on
for B=1:8
M = [2 3].^B
N = [2 4].*B
plot(N,M,'k')
end
If you want to store the result it's better to use for eample
for B=1:8
M.(sprintf('v%d',B))= [2 3].^B
N.(sprintf('v%d',B))= [2 4].*B
end
  댓글 수: 10
Azzi Abdelmalek
Azzi Abdelmalek 2012년 11월 14일
편집: Azzi Abdelmalek 2012년 11월 14일
use this
hold on;arrayfun(@(x) plot(M{x},N{x},'k'),1:numel(M))
Stephen
Stephen 2012년 11월 14일
Works perfectly; thank you very much for all the help :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by