Effacer les filtres
Effacer les filtres

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

2 vues (au cours des 30 derniers jours)
Minh Hoang
Minh Hoang le 8 Mar 2024
Commenté : Dyuman Joshi le 8 Mar 2024
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!

Réponse acceptée

Dyuman Joshi
Dyuman Joshi le 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
  2 commentaires
Minh Hoang
Minh Hoang le 8 Mar 2024
It worked! Thank you so much!
Dyuman Joshi
Dyuman Joshi le 8 Mar 2024
You're welcome!
You could vectorize your code as well. See - eye, flip

Connectez-vous pour commenter.

Plus de réponses (1)

Chuguang Pan
Chuguang Pan le 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

Catégories

En savoir plus sur Operating on Diagonal Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by