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 个评论
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!