Extract multiple matrix from a vector

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

Answers (2)

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 Comments

+1. That is better. I can't seem to remember this method although I've seen it several times.
Hi Fangjun! This idea belongs to Matt Fig (use strfind for this targets).

Sign in to comment.

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 Comments

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)?
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)

Sign in to comment.

Categories

Find more on MATLAB in Help Center and File Exchange

Asked:

on 15 Oct 2011

Community Treasure Hunt

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

Start Hunting!