Trouble with handling values in anti-diagonal of a square matrix

조회 수: 2 (최근 30일)
I am trying to create a square matrix whose diagonal and antidiagonal have the same value (let say, 8). However the antidiagonal values in the matrix I create do not act in the way I expect. Here is my code:
function outXmatrix = sqrtmatx(s) %a function whose input is the dimension of the square matrix
nrows = s;
A = zeros(nrows, nrows);
for c = 1:nrows
for r = 1:nrows
for i = 0:(nrows - 1)
if r == c
A(r,c) = 8; %Assign value 8 to the diagonal
elseif r == i+1 && c == nrows-i %Assign value 8 to the antidiagonal
A(r,c) = 8;
else %Assign value 1 to the other elements
A(r,c) = 1;
end
end
end
outXmatrix = A;
end
For example, s = 5
My expected matrix is
A = [8 1 1 1 8,
1 8 1 8 1,
1 1 8 1 1,
1 8 1 8 1,
8 1 1 1 8]
The matrix my function produced is
sqrtmatx(5)
I hope someone could point out the problem in my code. Thanks a lot!

채택된 답변

Dyuman Joshi
Dyuman Joshi 2024년 3월 8일
1 - Preallocate using ones() instead of zeros() and remove the else part.
2 - Update the condition for checking the anti-diagonal element, and remove the 3rd for loop.
y = sqrtmatx(5)
y = 5×5
8 1 1 1 8 1 8 1 8 1 1 1 8 1 1 1 8 1 8 1 8 1 1 1 8
y = sqrtmatx(8)
y = 8×8
8 1 1 1 1 1 1 8 1 8 1 1 1 1 8 1 1 1 8 1 1 8 1 1 1 1 1 8 8 1 1 1 1 1 1 8 8 1 1 1 1 1 8 1 1 8 1 1 1 8 1 1 1 1 8 1 8 1 1 1 1 1 1 8
function outXmatrix = sqrtmatx(s) %a function whose input is the dimension of the square matrix
nrows = s;
A = ones(nrows, nrows);
for c = 1:nrows
for r = 1:nrows
if r == c
A(r,c) = 8; %Assign value 8 to the diagonal
%% updated check for antidiagonal term
elseif r + c == s+1 %Assign value 8 to the antidiagonal
A(r,c) = 8;
end
end
outXmatrix = A;
end
end
  댓글 수: 2
Minh Hoang
Minh Hoang 2024년 3월 8일
It worked! Thank you so much!
Dyuman Joshi
Dyuman Joshi 2024년 3월 8일
You're welcome!
You could vectorize your code as well. See - eye, flip

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

추가 답변 (1개)

Chuguang Pan
Chuguang Pan 2024년 3월 8일
diagVal=8;
otherVal=1;
nrows=8;
if mod(nrows,2) % odd
A=(diagVal-otherVal)*eye(nrows) + (diagVal-otherVal)*fliplr(eye(nrows))+...
otherVal*ones(nrows);
A(ceil(nrows/2),ceil(nrows/2))=A(ceil(nrows/2),ceil(nrows/2))-(diagVal-otherVal);
else
% even
A=(diagVal-otherVal)*eye(nrows) + (diagVal-otherVal)*fliplr(eye(nrows))+...
otherVal*ones(nrows);
end
disp(A)
8 1 1 1 1 1 1 8 1 8 1 1 1 1 8 1 1 1 8 1 1 8 1 1 1 1 1 8 8 1 1 1 1 1 1 8 8 1 1 1 1 1 8 1 1 8 1 1 1 8 1 1 1 1 8 1 8 1 1 1 1 1 1 8

카테고리

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