# find the average of a vector with specific condition ?

3 views (last 30 days)

Show older comments

I had A vector

A=[1 0 0 2 3 2 3 5 0 0 0 0 1 2 1 0 0 0 0 3 4 0 0 0 0 0 0 1 2 3 2 0 0 0 0 2 0 0]

like this. Now I want a vector B having average of corresponding non-zero value, like

B(1)=average(A(1));

B(4)=average(A(4):A(8));

B(13)=average(A(13):A(15);

B(20)=average(A(20):A(21));

B(28)=average(A(28):A(31)) and so on .....rest values should be zeros.

hence

B=[1 0 0 3 0 0 0 0 0 0 0 0 1.33 0 0 0 0 0 0 3.5 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 2 0 0 ]

##### 5 Comments

jonas
on 4 Sep 2018

### Accepted Answer

jonas
on 4 Sep 2018

Edited: jonas
on 4 Sep 2018

A=[1 0 0 2 3 2 3 5 0 0 0 0 1 2 1 0 0 0 0 3 4 0 0 0 0 0 0 1 2 3 2 0 0 0 0 2 0 0];

B=zeros(size(A));

bounds = find(diff([0, A, 0] ~= 0));

starts = bounds(1:2:end);

ends = bounds(2:2:end) - 1;

B(starts) = arrayfun(@(s, e) mean(A(s:e)), starts, ends);

##### 4 Comments

jonas
on 4 Sep 2018

@Guillaume: Thank you sir, I'll update the code.

@Mukesh: The code should work now. There was a minor error in my original post. You were too quick to grab it :)

### More Answers (0)

### See Also

### Categories

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!