matlab中向量的连续非零数组的个数怎么求?

matlab里的向量a=[0 0 0 1 2 3 0 0 4 5 0 0 6 0 0],我想得出这个向量a中有3个连续非零数组(即[1 2 3]、[4 5]、[6])。我只需要知道有几个这种连续非零数组就行。代码如何实现?谢谢!

不仅给你求非零数组数,而且还给你分好组了,存在result里边。


a=[0 0 0 1 2 3 0 0 4 5 0 0 6 0 0];

temp=[];

result={};

while(~isempty(a))

    if a(1)==0

        if(~isempty(temp))

            result=[result,{temp}];

        end

        temp=[];

        flag=0;

    else

        temp=[temp,a(1)];

        flag=1;

    end

    a(1)=[];

end

disp(['非零段数为' num2str(length(result))]);


温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-03-19
length(a(a~=0));
相似回答