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

2 ビュー (過去 30 日間)
Minh Hoang
Minh Hoang 2024 年 3 月 8 日
コメント済み: Dyuman Joshi 2024 年 3 月 8 日
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 Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by