Is there a way to combine number of matrices into one?
10 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Jan
le 4 Avr 2019
Modifié(e) : Jan
le 4 Avr 2019
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{:})
Plus de réponses (1)
Stephan
le 4 Avr 2019
Modifié(e) : Stephan
le 4 Avr 2019
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
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!