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:
Replacing some # of values of an array with a different array of same # of values

Subject: Replacing some # of values of an array with a different array of same # of values

From: Nicolas

Date: 10 Oct, 2012 21:50:08

Message: 1 of 3

Hi all,

I hope my title makes sense. I have a feeling that what I am trying to do is not necessarily difficult, but I'm just not sure how to approach this problem without doing something extremely inefficient.

I have an array of values, e.g. :

temp = [1 2 3 50 1 2 3 60 1 2 3 50 1 2 3];

I want to find all instances of '50' and '60' and replace them with alternative values.

altern = [80 70 80];

The number of values that I identify in temp will always match the number of alternative values that I want to insert.

I was thinking that I would use find() to locate the desired indices of temp and then one by one replace those with altern in a for loop.

Any guidance is appreciated. Thanks!

Subject: Replacing some # of values of an array with a different array of same # of values

From: Roger Stafford

Date: 11 Oct, 2012 00:46:08

Message: 2 of 3

"Nicolas " <nickbedo@yahoo.com> wrote in message <k54qig$45d$1@newscl01ah.mathworks.com>...
> temp = [1 2 3 50 1 2 3 60 1 2 3 50 1 2 3];
> I want to find all instances of '50' and '60' and replace them with alternative values.
> altern = [80 70 80];
- - - - - - - - - -
  Use logical indexing:

 temp(temp==50|temp==60) = altern;

(It will be up to you to ensure that 'altern' has the correct number of elements.)

Roger Stafford

Subject: Replacing some # of values of an array with a different array of same # of values

From: Nicolas

Date: 11 Oct, 2012 01:26:07

Message: 3 of 3

"Roger Stafford" wrote in message <k554sg$86i$1@newscl01ah.mathworks.com>...
> "Nicolas " <nickbedo@yahoo.com> wrote in message <k54qig$45d$1@newscl01ah.mathworks.com>...
> > temp = [1 2 3 50 1 2 3 60 1 2 3 50 1 2 3];
> > I want to find all instances of '50' and '60' and replace them with alternative values.
> > altern = [80 70 80];
> - - - - - - - - - -
> Use logical indexing:
>
> temp(temp==50|temp==60) = altern;
>
> (It will be up to you to ensure that 'altern' has the correct number of elements.)
>
> Roger Stafford

Wow, that is so much simpler than I had imagined. Thanks so much!

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