From: Wendy on
Hi all,

I have a big square matrix, and I want to change the diagonal elements to 1. Is there a way that I can change the diagonal elements at once, instead of looping through all the elements one by one.

As an example,

A = [3 2 1;
4 5 6;
7 8 9];

and I want
A = [1 2 1;
4 1 6;
7 8 1].

Thanks,
Wendy
From: James Tursa on
"Wendy " <wlq121(a)gmail.com> wrote in message <i084bh$b3k$1(a)fred.mathworks.com>...
> Hi all,
>
> I have a big square matrix, and I want to change the diagonal elements to 1. Is there a way that I can change the diagonal elements at once, instead of looping through all the elements one by one.
>
> As an example,
>
> A = [3 2 1;
> 4 5 6;
> 7 8 9];
>
> and I want
> A = [1 2 1;
> 4 1 6;
> 7 8 1].
>
> Thanks,
> Wendy

[m n] = size(A);
A(1:m+1:end) = 1;

James Tursa