how to count non zero elements in a vector and replace this values based on the count values

Dear all,
I'm a new matlab user and in my case i have a vector let say: v= [0 0 0 0.1 0.2 0.3 0.4 0.5 0 0 0 0 0 0 0.1 0.2] I want to count consecutive non zero values i.e in my vector have first five nonzero values [0.1 0.2 0.3 0.4 0.5] and two last nozeros values[0.1 0.2] what I want is: count the consecutive non zero values and put a condition i.e if the length of nonzeros is greater then 3 (count>3) then the respective values of vector V(i) remain v(i) if the length consecutive values is less than three (count<3) then respective values of v(i) =0 I want to get a new vector let say v1 derivation from vector v where: v1= [0 0 0 0.1 0.2 0.3 0.4 0.5 0 0 0 0 0 0 0 0]
Any help would be appreciated Thank you DM

 採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2015 年 7 月 30 日
編集済み: Azzi Abdelmalek 2015 年 7 月 30 日
v= [0 0 0 0.1 0.2 0.3 0.4 0.5 0 0 0 0 0 0 0.1 0.2]
idx=[0 v~=0 0]
idx1=strfind(idx,[0 1])
idx2=strfind(idx,[1 0])-1
id=idx2-idx1+1
ii1=idx1(id>3)
ii2=idx2(id>3)
jj=cell2mat(arrayfun(@(x,y) x:y,ii1,ii2,'un',0))
out=zeros(size(v))
out(jj)=v(jj)

その他の回答 (2 件)

Andrei Bobrov
Andrei Bobrov 2015 年 7 月 30 日
編集済み: Andrei Bobrov 2015 年 7 月 30 日
v= [0 0 0 0.1 0.2 0.3 0.4 0.5 0 0 0 0 0 0 0.1 0.2]';
ii = v ~= 0;
t = [false;diff(ii)==1];
i1 = cumsum(t).*ii;
N = histcounts(i1,1:(max(i1)+1));
i1(ismember(i1,find(N <= 3))) = 0;
out = v.*i1;

2 件のコメント

D Marini
D Marini 2015 年 7 月 30 日
thank you andwer however unfourtnely this solution didn't work, i got this error:
Undefined function 'histcounts' for input arguments of type 'double'. Error in TESTHeatLossCalcDHWCatoffShortDraw (line 111) N = histcounts(i1,1:(max(i1)+1));
Sean de Wolski
Sean de Wolski 2015 年 7 月 30 日
histcounts is new in R2014b, if you're on an older release either upgrade or use histc.

サインインしてコメントする。

D Marini
D Marini 2015 年 7 月 30 日
Thank you Azzi,
The code seems to work OK, Just wonder if would be possible to explain how it works (for bigginers is difficult to understand).
Thank you very much again D,

カテゴリ

ヘルプ センター および File ExchangeData Distribution Plots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by