![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/173837/image.png)
Matrix from vectors (dynamic number of columns)
조회 수: 1 (최근 30일)
이전 댓글 표시
Dear Matlab users I want to create a matrix form vectors V1, V2 and V3 (same number of rows), number of rows equal to number of rows in vectors) but the number of column is dynamic (relative to an integer called Nbr), let explain with an example:
V1 = [1 2 3]
V1 = [4 5 6]
V1 = [7 8 9]
t = [0.1 0.2 0.3] % (used for an future plot)
If Nbr = 1 the matrix came
1
2
3
I plot (t, V1), the legend is Case1
If Nbr = 2 the matrix came
1 4
2 5
3 6
I plot (t, V1, t, V2), the legend is (Case1, Case2)
If Nbr = 3 the matrix came
1 4 7
2 5 8
3 6 9
I plot (t, V1, t, V2, t, V3), the legend is (Case1, Case2, Case3)
I attached the plot for the last case (Nbr = 3)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/158979/image.gif)
댓글 수: 0
답변 (2개)
Stephen23
2016년 3월 26일
편집: Stephen23
2016년 3월 26일
Putting all of your data into separate variables is a really bad idea, so the first thing to do is to save them in one matrix (I called it M). Then your whole task becomes trivial using basic MATLAB indexing, and you can also supply the whole matrix (or part of it) to plot instead of supplying separate input arguments. Much easier!
t = [0.1,0.2,0.3];
M = [1,2,3;4,5,6;7,8,9]; % your data
% create the legend strings:
C = arrayfun(@num2str,1:size(M,1),'uni',0);
C = strcat({'Case '},C);
% pick how many lines to plot:
N = 2;
plot(t,M(1:N,:).')
legend(C(1:N))
See how easy MATLAB can be? It creates this plot:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/173837/image.png)
EDIT: without the legend, to show how the matrix is plotted without wasting time using loops:
t = [0.1,0.2,0.3];
M = [1,2,3;4,5,6;7,8,9];
N = 2;
plot(t,M(1:N,:).')
Azzi Abdelmalek
2016년 3월 26일
편집: Azzi Abdelmalek
2016년 3월 26일
v=[1 2 3;4 5 6;7 8 9]
t = [0.1 0.2 0.3]
n=2
plot(t,v(:,1:n)')
legend(genvarname(repmat({'Case'},1,n),'Case'))
참고 항목
카테고리
Help Center 및 File Exchange에서 Legend에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!