How to create an array of matrices?

191 Ansichten (letzte 30 Tage)
Goncalo Costa
Goncalo Costa am 23 Jan. 2022
Beantwortet: Thomas am 22 Jun. 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...

Antworten (3)

the cyclist
the cyclist am 23 Jan. 2022
Bearbeitet: the cyclist am 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 Kommentar
Goncalo Costa
Goncalo Costa am 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.

Melden Sie sich an, um zu kommentieren.


the cyclist
the cyclist am 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 am 22 Jun. 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.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by