From: davidebacc Bacchini on
What is the command to modify a matrix diagonal? I want it set to zero

M=[1 2 3;4 5 6; 7 8 9]
result=[0 2 3;4 0 6; 7 8 0]

I tried diag(M)=0; but doesnt work
Thank you
From: John D'Errico on
"davidebacc Bacchini" <davidebacc(a)hotmail.com> wrote in message <hk9agi$c0p$1(a)fred.mathworks.com>...
> What is the command to modify a matrix diagonal? I want it set to zero
>
> M=[1 2 3;4 5 6; 7 8 9]
> result=[0 2 3;4 0 6; 7 8 0]
>
> I tried diag(M)=0; but doesnt work
> Thank you

Why would that possibly work anyway?

Perhaps this is an alternative, since diag is its own
"inverse".

M = M - diag(diag(M));

This is not the best solution if M is large of course.

John
From: Matt J on

Another solution.

n=size(M,1);
M(1:n+1:n^2)=0;
From: Jos (10584) on
"davidebacc Bacchini" <davidebacc(a)hotmail.com> wrote in message <hk9agi$c0p$1(a)fred.mathworks.com>...
> What is the command to modify a matrix diagonal? I want it set to zero
>
> M=[1 2 3;4 5 6; 7 8 9]
> result=[0 2 3;4 0 6; 7 8 0]
>
> I tried diag(M)=0; but doesnt work
> Thank you

Here is a matlabish way:

M = magic(4) % test data
TF = eye(size(M)) == 1 % which elements belong to the diagonal
M(TF) = 0 % set them to zero

Jos