How to iterate across a specific diagonal?

조회 수: 2 (최근 30일)
Karen Smith
Karen Smith 2021년 12월 28일
댓글: Karen Smith 2021년 12월 28일
Hello, I am a beginner to matlab and wondering if anyone can help me with this specific problem. Here is my code
N1=2;
N2=2;
nband=1;
n=(N1*N2)*2*nband;
t=4;
HM = zeros(n);
% upper t diagonal
for ii = (N1*N2*nband):n
HM(ii,n+1-ii) = t
end
HM
% end
What I am trying to do is get a diagonal of 4's or the t variable across the the half diagonal of the matrix. Here is an image for reference. It must work for all values of N1 and N2. For example, if N1 =3, N2=2, then I would like the 8th diagonal to be iterated through the t variable. It is basically half of the n dimension. I am stuck. Any help is appreciated if possible! Thank you so much
  댓글 수: 1
Stephen23
Stephen23 2021년 12월 28일
Why use a loop?
fliplr(diag(4*ones(1,4),4))
ans = 8×8
0 0 0 4 0 0 0 0 0 0 4 0 0 0 0 0 0 4 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

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

채택된 답변

Voss
Voss 2021년 12월 28일
N1=2;
N2=2;
nband=1;
n=(N1*N2)*2*nband;
t=4;
HM = zeros(n);
% upper t diagonal
for ii = 1:(N1*N2*nband)
HM(ii,(N1*N2*nband)+1-ii) = t;
end
HM
HM = 8×8
0 0 0 4 0 0 0 0 0 0 4 0 0 0 0 0 0 4 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by