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
0 件のコメント
採用された回答
DJ V
2016 年 11 月 12 日
1 件のコメント
Walter Roberson
2016 年 11 月 13 日
Please click on "Comment on this Answer" instead of creating a new Answer.
その他の回答 (2 件)
Walter Roberson
2016 年 11 月 12 日
n:n-1:something
3 件のコメント
Ahmet Cecen
2016 年 11 月 12 日
Oh yeah, you can also use linear indexing. Huh didn't even think of that.
Walter Roberson
2016 年 11 月 13 日
Another hint:
Z = zeros(3,3);
Z(sub2ind([3 3], [1 2 3], [3 2 1])) = 1
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()
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Operating on Diagonal Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!