Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
vector manipulation

Subject: vector manipulation

From: Joel

Date: 24 Apr, 2009 22:51:49

Message: 1 of 2

I am trying to model diffusion and am trying to avoid a for loop:

'dist' = vector with each column representing a place on a horizontal axis and each number representing the number of particles at the place.
'non_zero' = vector with the index of each non_zero element (occupied place) from dist

I want to create a new vector 'c' that has each index appearing as many times as particles occupy that index in dist (if dist(1) = 5, c(1:5)= (1 1 1 1 1 ))

any way to avoid the for loop? Thanks!

Subject: vector manipulation

From: Roger Stafford

Date: 25 Apr, 2009 03:10:04

Message: 2 of 2

Joel <hacefrio_02@hotmail.com> wrote in message <14266937.6840.1240613540267.JavaMail.jakarta@nitrogen.mathforum.org>...
> I am trying to model diffusion and am trying to avoid a for loop:
> 'dist' = vector with each column representing a place on a horizontal axis and each number representing the number of particles at the place.
> 'non_zero' = vector with the index of each non_zero element (occupied place) from dist
> I want to create a new vector 'c' that has each index appearing as many times as particles occupy that index in dist (if dist(1) = 5, c(1:5)= (1 1 1 1 1 ))
> any way to avoid the for loop? Thanks!

  Yes. Let d be 'dist' and n be 'non_zero', where both are row vectors.

 s = cumsum(d(n)).';
 c = cumsum(accumarray([1;s(1:end-1)+1;s(1:end-1)+1],[n,-n(1:end-1)],s(end))).';

  I'm not sure I see how this ties in with modeling diffusion.

Roger Stafford

Tags for this Thread

No tags are associated with this thread.

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.

Contact us