Find the mean of a specific set of values in matrix/vector

1 view (last 30 days)
If I have a vector of #'s and zeroes
ex. z=[ 0 0 0 2 3 4 0 0 0 0 0 6 7 8 0 0 0 13 18 22]
and I want to replace the numbers that are together that are not equal to 0 with the mean value of those set of numbers to give.
ex. z = [ 0 0 0 3 3 3 0 0 0 0 0 7 7 7 0 0 0 17.66 17.66 17.66]
How do I do this?

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 3 Nov 2013
z=[ 0 0 0 2 3 4 0 0 0 0 0 6 7 8 0 0 0 13 18 22];
idx=[0 logical(z) 0];
ii1=strfind(idx,[0,1]);
ii2=strfind(idx,[1,0])-1;
for k=1:numel(ii1)
z(ii1(k):ii2(k))=mean(z(ii1(k):ii2(k)));
end
disp(z)

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!