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

2 views (last 30 days)
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!

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 8 Mar 2024
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

More Answers (1)

Chuguang Pan
Chuguang Pan on 8 Mar 2024
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

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!