Extract multiple matrix from a vector

1 回表示 (過去 30 日間)
Jean
Jean 2011 年 10 月 15 日
Hello to all,
Say you have a vector containing zones with consecutive values of zero and zones with numbers other than zero, like in the example:
v = [1 2 3 5 5 0 0 0 0 1 4 2 0 0 5 8 0 0 1 5 8 5 0 0 0]
Nevertheless, imagine that in the actual vector I have the non zero and zero zones vary in length from a couple of hundred to a couple pf thousand points.
I need to extract from my vector the non zero zones and place them into a cell array (say for example zones{} because the non zero zones have different lengths) and so far the my efforts did not output a good result (I tried manipulating the index with "find(v == 0)"). Has anybody encountered this challenge?
Best regards, Jean

回答 (2 件)

Andrei Bobrov
Andrei Bobrov 2011 年 10 月 19 日
v = [1 2 3 5 5 0 0 0 0 1 4 2 0 0 5 8 0 0 1 5 8 5 0 0 0];
v1 = v~=0;
out = arrayfun(@(x,y)v(x:y),strfind([0 v1],[0 1]),strfind([v1 0] ,[1 0]),'un',0);
  2 件のコメント
Fangjun Jiang
Fangjun Jiang 2011 年 10 月 19 日
+1. That is better. I can't seem to remember this method although I've seen it several times.
Andrei Bobrov
Andrei Bobrov 2011 年 10 月 20 日
Hi Fangjun! This idea belongs to Matt Fig (use strfind for this targets).

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


Fangjun Jiang
Fangjun Jiang 2011 年 10 月 16 日
v = [0 1 12 3 5 55 0 0 0 0 1 4 22 0 0 5 8 0 0 1 5 85 5 0 0 0 12 0];
s=num2str(v);
c=regexp(s,'0\s|\s0','split');
d=cellfun(@str2num,c,'uni',false);
e=cellfun('isempty',d);
f=d(~e);
celldisp(f)
f{1} =
1 12 3 5 55
f{2} =
1 4 22
f{3} =
5 8
f{4} =
1 5 85 5
f{5} =
12
  2 件のコメント
Jean
Jean 2011 年 10 月 19 日
Hello,
Thank you very much for your answer. However, can you tell me how to get the indexes of these values (it will be useful in my algorithm)?
Fangjun Jiang
Fangjun Jiang 2011 年 10 月 19 日
Use the following code to get the starting position of each non-zero zone.
%%
v = [0 1 12 3 5 55 0 0 0 0 1 4 22 0 0 5 8 0 0 1 5 85 5 0 0 0 12 0];
NonZeroFlag=v~=0;
NonZeroIndex=find(NonZeroFlag);
t=diff([0, NonZeroIndex]);
index=find(t-1);
Pos=NonZeroIndex(index)
CheckValue=v(Pos)

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by