Matrix from vectors (dynamic number of columns)
2 次查看(过去 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)
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:
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 中查找有关 Data Distribution Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!