Trouble with handling values in anti-diagonal of a square matrix
Show older comments
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
More Answers (1)
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)
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!