I need to produce a matrix that has one's along the diagonal from the upper right to the lower left

조회 수: 18 (최근 30일)
I need to produce a matrix along a square matrix of size "n" that has one's along the diagonal from the upper right to the lower left. I can't use "for" or an "if" statement. Any idea?
What doesn't work is:
function Y = reverse_diag(n)
zeroes = zero(n);
x = zero;
x(1:1:n,n:-1:1) =1;
Y = x;
end

채택된 답변

DJ V
DJ V 2016년 11월 12일
Thanks, but use of diag is explicit;y forbidden.

추가 답변 (2개)

Walter Roberson
Walter Roberson 2016년 11월 12일
n:n-1:something
  댓글 수: 3
Ahmet Cecen
Ahmet Cecen 2016년 11월 12일
Oh yeah, you can also use linear indexing. Huh didn't even think of that.

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


Ahmet Cecen
Ahmet Cecen 2016년 11월 12일
x(1:1:n,n:-1:1) =1;
You cannot index points inside a matrix like that. MATLAB indexing reads like this:
Matrix(a,b) => For every a corresponding to every b.
So what you are doing is, say for the first row, fill every column (n:-1:1), then for the second row and so forth.
What you need to do is either use a for loop manually, or use the function:
diag()
followed by the function:
fliplr()

카테고리

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