Extract multiple matrix from a vector
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(2 个)
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
2011-10-19
+1. That is better. I can't seem to remember this method although I've seen it several times.
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 个评论
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)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!