How to create an array of matrices?

176 visualizaciones (últimos 30 días)
Goncalo Costa
Goncalo Costa el 23 de En. de 2022
Respondida: Thomas el 22 de Jun. de 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...

Respuestas (3)

the cyclist
the cyclist el 23 de En. de 2022
Editada: the cyclist el 23 de En. de 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 comentario
Goncalo Costa
Goncalo Costa el 23 de En. de 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.

Iniciar sesión para comentar.


the cyclist
the cyclist el 23 de En. de 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 el 22 de Jun. de 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.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by