1
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.

user3495562
  • 335
  • 1
  • 4
  • 16
  • 1
    see http://stackoverflow.com/questions/3963565/how-to-assign-values-on-the-diagonal – Nasser Apr 21 '14 at 03:16
  • For the [generic approach to troubleshoot this error](http://stackoverflow.com/a/20054048/983722), see [this question](http://stackoverflow.com/q/20054047/983722). – Dennis Jaheruddin May 26 '14 at 15:38

3 Answers3

1

you can just use linear indexing, for example, ifM is 3x3:

 M(1:(size(M,1)+1):end)=[10 20 30]
bla
  • 25,846
  • 10
  • 70
  • 101
1

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
Divakar
  • 218,885
  • 19
  • 262
  • 358
0

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
Rafael Monteiro
  • 4,509
  • 1
  • 16
  • 28