Combining sub-matrices diagonally within a for loop

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!

 채택된 답변

Bruno Luong
Bruno Luong 2019년 8월 13일
submats = arrayfun(@(n) 2*(1:n)'+(1:n),[3 1 2],'unif',0)
matrix = blkdiag(submats{:})

댓글 수: 4

% Thanks for the answer but I need more explanation because
% I have a much bigger matrix than n= [3 2 1]
% Is it fine to change the matrix as:
submats = arrayfun(@(n) 2*(1:n)'+(1:n),n,'unif',0);
matrix = blkdiag(submats{:});
% What is the function of @(n)? Which part of the code gives me
% length(n)=3? It is important for the original code I am working on.
"What is the function of @(n)?"
I would really appreciate if you can look at my similar question on https://www.mathworks.com/matlabcentral/answers/475992-combination-of-sub-matrices-generated-within-a-for-loop? Your suggestion is cool, I really like to apply it!
I actually wait to see what do you learn and how you manage to adatp the above code to this tiny change.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Rengin
Rengin 2019년 8월 13일

0 개 추천

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

댓글 수: 2

Bruno Luong
Bruno Luong 2019년 8월 13일
편집: Bruno Luong 2019년 8월 13일
n=[3 1 2];
rad=[0.04 0.02 0.01];
h=[10 12 15];
submats = arrayfun(@(n,r,h) r*h*ones(n),n,rad,h,'unif',0);
...
Now I understand better! Thanks a lot

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

질문:

2019년 8월 13일

댓글:

2019년 8월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by