Submatrices into a Structured Larger Matrix

Hi,
I need a code to create a lower triangular matrix consisting of several submatrices, where each submatrix has its own coordinates [between (xi_0,yi_0) and (xi_f,yi_f)] without any use of for loop.
i.e. Submatrices A, B and C are each 3x3 matrices. I want to create a D matrix as: [A zeros(3x3);B C]
Any help could be useful.
Thanks in advance!

3 Comments

My first attempt is:
A=randn(3,18);
B=zeros(3,27);
layers=[1:3 10:15 19:27];
B(:,layers)=A
C=mat2cell(B,ones(1,1)*3,ones(3,1)*9)
vertcat(C{:})
Hard to understand what you want. Please provide a simple example of A,B,C and the desired output.
In this simple example, there are 3 matrices, mainly A, B and C.
I want to place these matrices into a lower triangular matrix form:
[A zeros(3x3);
B C]
A=[1 2 3;4 5 6;7 8 9]
B=[10 11 12;13 14 15;16 17 18]
C=[19 20 21;22 23 24;25 26 27]
Output: [1 2 3 0 0 0;
4 5 6 0 0 0;
7 8 9 0 0 0;
10 11 12 19 20 21
13 14 15 22 23 24
16 17 18 25 26 27]
In general form, I have over hundreds of matrices (A1, A2, A3, A4, ... A100) that should be placed as follows:
[A1
A2 A3
A4 A5 A6
...]
Thank you!

Sign in to comment.

Answers (1)

Adjust as necessary. Need 105 3x3 matrices to fill described pattern above. I assume all A matrices are the same size (3x3).
for k=1:105
A{k}=randi(100,3);%fill A cell array with 3x3 matrices. Recommend you place all your matrices into a cell array or 3D array
A2(:,:,k)=randi(100,3);%3D array instead of cell array
end
B=zeros(1,42);
B2=B;
c=1;
for m=1:14
for n=1:m
B((m-1)*3+1:3*m,(n-1)*3+1:3*n)=A{c};%either storage system will work (A or A2)
B2((m-1)*3+1:3*m,(n-1)*3+1:3*n)=A2(:,:,c);
c=c+1;
end
end

3 Comments

I was looking for a way that doesn't utilize any for loops, like in this example I gave earlier:
A=randn(3,18);
B=zeros(3,27);
layers=[1:3 10:15 19:27]; (columns 4:9, 16:18 are zeros)
B(:,layers)=A
C=mat2cell(B,ones(1,1)*3,ones(3,1)*9)
vertcat(C{:})
Thanks for the answer though.
There is nothing wrong with loops, especially when having to index into a variable. You should never label variables like A1, A2, A3, ......, A100, but rather store then into an array that can be indexed.
Why are you looking for a way that doesn't utilize any for loops? mat2cell() uses for loops internally -- you can read the source code.

Sign in to comment.

Asked:

on 17 Oct 2022

Commented:

on 17 Oct 2022

Community Treasure Hunt

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

Start Hunting!