Extract multiple matrix from a vector

조회 수: 3 (최근 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 CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by