diag(M) = c(1,2,3)
say I have a matrix M 3*3, then I want to assign value to its diagnal elements, but above command line does not work why?
The errors says Subscript indices must either be real positive integers or logicals.
diag(M) = c(1,2,3)
say I have a matrix M 3*3, then I want to assign value to its diagnal elements, but above command line does not work why?
The errors says Subscript indices must either be real positive integers or logicals.
you can just use linear indexing, for example, ifM
is 3x3:
M(1:(size(M,1)+1):end)=[10 20 30]
You can use diag
this way -
%%// Given matrix M
M = randi(10,3,3)
%%// Assign the diagonal elements as 1,2,3
M(diag(ones(size(M,1),1),0)>0) = 1:3
Output -
M =
3 1 2
3 5 8
6 2 3
M =
1 1 2
3 2 8
6 2 3
You can do it with the identity matrix:
>> M = rand(3)
M =
0.3922 0.7060 0.0462
0.6555 0.0318 0.0971
0.1712 0.2769 0.8235
>> M(eye(size(M)) == 1) = [1 2 3]
M =
1.0000 0.7060 0.0462
0.6555 2.0000 0.0971
0.1712 0.2769 3.0000