Is there a way to combine number of matrices into one?
9 ビュー (過去 30 日間)
古いコメントを表示
Hi there, I would like to ask is there a way to join multiple matrices into a single one in a better way?
I was thinking maybe a for loop could do the job, but I don't know where to start as each data contains a different name.
For Example: Suppose I have 10 matrices, it is in the workspace as various name but equal sizes.
e.g) for all matrices in 10x10 size
matrix1_10
matrix11_20
matrix21_30.....
matrix91_100
I would like to join them into a column, so like 100x10 size matrix
I do know there is a way to do this.
If I would like to join each other vertically, well I could do [matrix1_10; matrix11_20 ; matrix21_30 ; ...... ; matrix91_100], it will do just fine.
However if the number of data was not 10 matrices, could be 1000, 10000 or more, what should I do in order to get the job done?
Like I said, probably a for loop may help me on this case. But I don't know what to begin with? Or is there a better solution to this?
Thank you.
0 件のコメント
採用された回答
Jan
2019 年 4 月 4 日
編集済み: Jan
2019 年 4 月 4 日
If you have 1000 arrays, it would be a really bad idea to store them in different variables, e.g. by hinding an index in the name of the variable. See TUTORIAL: Why and how to avoid Eval
If you use a cell array instead, the solution is trivial:
matrix = cell(1, 10);
for k = 1:10
matrix = cell(10, 10);
end
% Join the matrices vertically:
result = cat(1, matrix{:})
その他の回答 (1 件)
Stephan
2019 年 4 月 4 日
編集済み: Stephan
2019 年 4 月 4 日
Hi,
this solution is evil - since it uses eval:
A = whos;
A = {A.name};
B = string(ones(1,2*numel(A)-1));
B(2:2:end) = ",";
for k = 1:numel(A)
B(2*k-1) = A{k};
end
M = eval(join(['vertcat(',B,')']));
To use it make sure that only your variables are in workspace you want to join!
Example:
clear
M1 = zeros(3)
M2 = ones(3)
M3 = M1
M4 = randi(10,3)
results in
M1 =
0 0 0
0 0 0
0 0 0
M2 =
1 1 1
1 1 1
1 1 1
M3 =
0 0 0
0 0 0
0 0 0
M4 =
10 4 5
2 1 10
3 7 5
After running the script:
>> M
M =
0 0 0
0 0 0
0 0 0
1 1 1
1 1 1
1 1 1
0 0 0
0 0 0
0 0 0
10 4 5
2 1 10
3 7 5
But note that this is bad style - read here:
Best regards
Stephan
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!