![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/173837/image.png)
Matrix from vectors (dynamic number of columns)
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposte (2)
Stephen23
il 26 Mar 2016
Modificato: Stephen23
il 26 Mar 2016
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
il 26 Mar 2016
Modificato: Azzi Abdelmalek
il 26 Mar 2016
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'))
2 Commenti
Vedere anche
Categorie
Scopri di più su Legend in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!