Thread Subject: how to vectorize this

Subject: how to vectorize this

From: Xiao Chen

Date: 25 Dec, 2007 08:28:06

Message: 1 of 3

Hi
A very simple question:
I want to replace the diagonals of a matrix.
for example,
a=[1 1 1
   1 1 1
   1 1 1]
I need to change 1 in the diagonals to 2, and the result
a=[2 1 1
   1 2 1
   1 1 2]
I can write this code in a For loop.
I'm sure there is a much better way to do the same job,
hmmm, writing it in a vectorized form. But I have not been
able to figure one out.

Can somebody help me, thanks!!!

Subject: how to vectorize this

From: Markus Buehren

Date: 29 Dec, 2007 19:09:29

Message: 2 of 3

If you have a square matrix with N rows and columns, you can
index the diagonal elements like this:

N=3;
A=ones(N);
A(1:(N+1):end)=2
A =
     2 1 1
     1 2 1
     1 1 2

Regards
Markus

Subject: how to vectorize this

From: Rick Rosson

Date: 30 Dec, 2007 05:41:13

Message: 3 of 3


Hi Xiao,

Another possible approach:

    N = 3;
    A = ones(N);
    idx = logical(eye(N));
    A(idx) = 2;

I hope that helps. Thank you very much.

Rick Rosson


"Markus Buehren" <mb_matlab.REMOVE@gmxTHIS.de> wrote in message
<fl6619$3cp$1@fred.mathworks.com>...
> If you have a square matrix with N rows and columns, you can
> index the diagonal elements like this:
>
> N=3;
> A=ones(N);
> A(1:(N+1):end)=2
> A =
> 2 1 1
> 1 2 1
> 1 1 2
>
> Regards
> Markus

Tags for this Thread

Everyone's Tags:

Add a New Tag:

Separated by commas
Ex.: root locus, bode

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Tag Activity for This Thread
Tag Applied By Date/Time
logical Rick Rosson 30 Dec, 2007 00:45:00
diagonal matrix Rick Rosson 30 Dec, 2007 00:45:00
eye Rick Rosson 30 Dec, 2007 00:45:00
vectorization Rick Rosson 30 Dec, 2007 00:44:59
vectorize xiao chen 25 Dec, 2007 03:30:21
rssFeed for this Thread

Contact us at files@mathworks.com