Combining sub-matrices diagonally within a for loop

2 views (last 30 days)
Rengin
Rengin on 13 Aug 2019
Commented: Rengin on 13 Aug 2019
clear all;
clc;
close all;
n=[3 1 2];
for kk=1:length(n)
matrix=zeros(n(kk),n(kk));
for ii=1:n(kk)
for jj=1:n(kk)
val=2*ii+jj;
matrix(ii,jj)=val;
end
end
end
% Dear users, if you put a debug at the very last "end" (row 13), you can
% see that I aim to generate 3 sub-matrices having the size of 3x3, 1x1 and
% 2x2 (see n=[3 1 2]). I want to combine each sub-matrix one each other diagonally.
% I want to get the matrix as a result below:
matrix=[3 4 5 0 0 0;5 6 7 0 0 0;7 8 9 0 0 0;0 0 0 3 0 0;0 0 0 0 3 4;0 0 0 0 5 6];
%Is there any simple way to do it?
%Thanks in advance!

Accepted Answer

Bruno Luong
Bruno Luong on 13 Aug 2019
submats = arrayfun(@(n) 2*(1:n)'+(1:n),[3 1 2],'unif',0)
matrix = blkdiag(submats{:})
  4 Comments
Bruno Luong
Bruno Luong on 13 Aug 2019
I actually wait to see what do you learn and how you manage to adatp the above code to this tiny change.

Sign in to comment.

More Answers (1)

Rengin
Rengin on 13 Aug 2019
I actually tried the combination of submats = arrayfun(@(n) rad(1:n)*h(1:n),n,'unif',0) but it didn't work.
  2 Comments

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by