How can I iterate across the opposite diagonal?

조회 수: 11 (최근 30일)
Karen Smith
Karen Smith 2021년 12월 24일
편집: DGM 2021년 12월 25일
Hi everyone, I am new to matlab and trying to build a matrix in it. I am wanting to know how to iterate across the other diagonal, opposite to where the 6's are. If anyone can do this with a similar for loop, all help would be appreciated. Thank you!
N1=2;
N2=2;
nband=1;
n= (N1* N2)*2*nband;
eps_s=1;
eps_sp=2;
eps_spp=3;
tp=4;
tps=5;
HM = zeros(n);
for ii = 1:n
HM(ii,ii) = 6; % (ii,ii) = eps_s
HM(ii,ii+1) = 4;
HM(ii+1,ii) = 4
end
  댓글 수: 3
Karen Smith
Karen Smith 2021년 12월 25일
pls elaborate if possible!!
Torsten
Torsten 2021년 12월 25일
If you set
for ii = 1:n
HM(ii,n+1-ii) = 6;
end
you set the opposite diagonal to 6.
For ii=1, you set HM(1,n) = 6.
For ii=2, you set HM(2,n-1) = 6.
...
For ii=n, you set HM(n,1) = 6.

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

답변 (3개)

Image Analyst
Image Analyst 2021년 12월 25일
At the end of your loop, just add
HM = fliplr(HM);
or else here is one way:
N1=2;
N2=2;
nband=1;
n= (N1* N2)*2*nband;
eps_s=1;
eps_sp=2;
eps_spp=3;
tp=4;
tps=5;
HM = zeros(n);
for ii = 1:n
col = n-ii+1;
if col <= n && col >= 1
HM(ii, col) = 6; % (ii,ii) = eps_s
end
col = n-ii+2;
if col <= n && col >= 1
HM(ii, col) = 4;
end
col = n-ii;
if col <= n && col >= 1
HM(ii, col) = 4;
end
end
HM

Sean de Wolski
Sean de Wolski 2021년 12월 25일
full(flip(gallery('tridiag', 8, 4, 6, 4), 2))
ans = 8×8
0 0 0 0 0 0 4 6 0 0 0 0 0 4 6 4 0 0 0 0 4 6 4 0 0 0 0 4 6 4 0 0 0 0 4 6 4 0 0 0 0 4 6 4 0 0 0 0 4 6 4 0 0 0 0 0 6 4 0 0 0 0 0 0

DGM
DGM 2021년 12월 25일
편집: DGM 2021년 12월 25일
You can also do:
HM = fliplr(toeplitz([6 4 zeros(1,7)]))
HM = 9×9
0 0 0 0 0 0 0 4 6 0 0 0 0 0 0 4 6 4 0 0 0 0 0 4 6 4 0 0 0 0 0 4 6 4 0 0 0 0 0 4 6 4 0 0 0 0 0 4 6 4 0 0 0 0 0 4 6 4 0 0 0 0 0 4 6 4 0 0 0 0 0 0 6 4 0 0 0 0 0 0 0
That said, it's unclear whether you're actually intending for the output to be 8x8 or 9x9. You assert n=8, and you preallocate an 8x8 array, but your indexing forces the array to be expanded to 9x9. Consequently, you're missing a 6 in the corner element. If the desired output is only 8x8, then that's as simple as changing the number of zeros.
HM = fliplr(toeplitz([6 4 zeros(1,6)]))

카테고리

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