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:
Replace odd elements with average of even elements

Subject: Replace odd elements with average of even elements

From: sushma sharma

Date: 11 Jan, 2010 23:40:20

Message: 1 of 4

Hi,

I have a one dimensional array: a = rand(100,1).

How can I write a simple script to replace the odd elements with the average of the even elements? (i.e. replace each odd value with the average of the even elements before and after it!)

Thank you!

S

Subject: Replace odd elements with average of even elements

From: Nathan

Date: 12 Jan, 2010 00:08:08

Message: 2 of 4

On Jan 11, 3:40 pm, "sushma sharma" <aim12...@gmail.com> wrote:
> Hi,
>
> I have a one dimensional array: a = rand(100,1).
>
> How can I write a simple script to replace the odd elements with the average of the even elements? (i.e. replace each odd value with the average of the even elements before and after it!)
>
> Thank you!
>
> S

You mean something like this?

a(1:2:end) = mean(a(2:2:end));

-Nathan

Subject: Replace odd elements with average of even elements

From: Matt Fig

Date: 12 Jan, 2010 00:10:21

Message: 3 of 4

% Data
A = randperm(6) % Also works for randperm(7);


% Engine.
E = A(2:2:end);
A(3:2:end-mod(length(A),2)) = mean([E(1:end-1);E(2:end)])
% Notes: does nothing to endpoints, as this wasn't specified.

Subject: Replace odd elements with average of even elements

From: Jos (10584)

Date: 12 Jan, 2010 09:23:05

Message: 4 of 4

"sushma sharma" <aim120c5@gmail.com> wrote in message <higct4$5iu$1@fred.mathworks.com>...
> Hi,
>
> I have a one dimensional array: a = rand(100,1).
>
> How can I write a simple script to replace the odd elements with the average of the even elements? (i.e. replace each odd value with the average of the even elements before and after it!)
>
> Thank you!
>
> S

So for an array [a1 a2 a3 a4 ... an], you want it become [a1 a2 (a2+a4)/2 a4 ...]
What happens to a1, and also an when n is odd?

Here is a possible but simple approach:

A = [10 2 4 3 7 5 4 5 9 6 4]
idx = 3:2:numel(A)-1 ;
B = A ;
B(idx) = (A(idx+1) + A(idx-1))/2

hth
Jos

Tags for 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