How to create an array of matrices?

197 visualizzazioni (ultimi 30 giorni)
Goncalo Costa
Goncalo Costa il 23 Gen 2022
Risposto: Thomas il 22 Giu 2023
If I have 3 matrices:
A = [1 2 ; 3 4]
B = [5 6 ; 7 8]
C = [9 10 ; 11 12]
And I want to create a greater matrix with these inside like D = [A ; B ; C], that would result in something like:
D = [1 2 ; 5 6 ; 9 10
3 4 ; 7 8 ; 11 12 ]
I have tried writing something as simple as
D = [A , B , C]
But this solely puts all these matrices side by side into a single matrix, whilst I intend to keep them all separately in an array, to create a "row" of matrices...

Risposte (3)

the cyclist
the cyclist il 23 Gen 2022
Modificato: the cyclist il 23 Gen 2022
You could use a cell array:
A = [1 2 ; 3 4];
B = [5 6 ; 7 8];
C = [9 10 ; 11 12];
D = {A, B, C}
D = 1×3 cell array
{2×2 double} {2×2 double} {2×2 double}
I think the best answer will depend on what you are planning on doing with the result afterward.
  1 Commento
Goncalo Costa
Goncalo Costa il 23 Gen 2022
I am trying to go through each matrix in a for loop. But when I tried writing it that way, I thought that the answer you showed below meant it hadn't worked, and that therefore I couldn't use this for a for loop.
Thank you so much for your help.

Accedi per commentare.


the cyclist
the cyclist il 23 Gen 2022
Given your comment on my other answer, another possible solution is to stack the matrices as slices in a 3rd dimension:
A = [1 2 ; 3 4];
B = [5 6 ; 7 8];
C = [9 10 ; 11 12];
D = cat(3,A,B,C);
for ii = 1:3
D(:,:,ii)
end
ans = 2×2
1 2 3 4
ans = 2×2
5 6 7 8
ans = 2×2
9 10 11 12

Thomas
Thomas il 22 Giu 2023
function aM = arrayofmatrices(A,B,C)
aM(:,:,1) = A;
aM(:,:,2) = B;
aM(:,:,3) = C;
end
This only works when A, B and C have the same sidelenths. If not you need a cell array.

Categorie

Scopri di più su Loops and Conditional Statements 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!

Translated by