How to create an array of matrices?

198 vues (au cours des 30 derniers jours)
Goncalo Costa
Goncalo Costa le 23 Jan 2022
Réponse apportée : Thomas le 22 Juin 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...

Réponses (3)

the cyclist
the cyclist le 23 Jan 2022
Modifié(e) : the cyclist le 23 Jan 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 commentaire
Goncalo Costa
Goncalo Costa le 23 Jan 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.

Connectez-vous pour commenter.


the cyclist
the cyclist le 23 Jan 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 le 22 Juin 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.

Catégories

En savoir plus sur Loops and Conditional Statements 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!

Translated by