Extract multiple matrix from a vector

2 visualizaciones (últimos 30 días)
Jean
Jean el 15 de Oct. de 2011
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

Respuestas (2)

Andrei Bobrov
Andrei Bobrov el 19 de Oct. de 2011
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 comentarios
Fangjun Jiang
Fangjun Jiang el 19 de Oct. de 2011
+1. That is better. I can't seem to remember this method although I've seen it several times.
Andrei Bobrov
Andrei Bobrov el 20 de Oct. de 2011
Hi Fangjun! This idea belongs to Matt Fig (use strfind for this targets).

Iniciar sesión para comentar.


Fangjun Jiang
Fangjun Jiang el 16 de Oct. de 2011
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 comentarios
Jean
Jean el 19 de Oct. de 2011
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 el 19 de Oct. de 2011
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)

Iniciar sesión para comentar.

Categorías

Más información sobre MATLAB en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by