Clear Filters
Clear Filters

How to create an array of matrices?

130 views (last 30 days)
Goncalo Costa
Goncalo Costa on 23 Jan 2022
Answered: Thomas on 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...

Answers (3)

the cyclist
the cyclist on 23 Jan 2022
Edited: the cyclist on 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 Comment
Goncalo Costa
Goncalo Costa on 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.

Sign in to comment.


the cyclist
the cyclist on 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 on 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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!