필터 지우기
필터 지우기

Splitting a vector into 'on' periods

조회 수: 1 (최근 30일)
CarrotCakeIsYum
CarrotCakeIsYum 2015년 9월 24일
댓글: Star Strider 2015년 9월 28일
Hi,
I'm investigating data from a force plate (study of balance in people with movement disorders). I have a raw signal such as:
vector = 1 2 3 4 0 0 0 0 5 6 7 4 7 8 0 0 0 1 2 5 4 0 0 0 0 0 5 6
I need to split this signal into separate vectors that only contain sequences of numbers greater than 0. So the ideal result for the above would be:
vector 1 = 1 2 3 4
vector 2 = 5 6 7 4 7 8
vector 3 = 1 2 5 4
vector 4 = 5 6
I hope the question is clear enough. Any help would be greatly appreciated!

채택된 답변

Star Strider
Star Strider 2015년 9월 24일
I did my best to make this as robust as possible:
vector = [1 2 3 4 0 0 0 0 5 6 7 4 7 8 0 0 0 1 2 5 4 0 0 0 0 0 5 6];
vec_nz = vector > 0; % Non-Zero Elements
dv = diff([0 vec_nz 0]); % Index Vector
on = find(dv > 0);
off = find(dv < 0);
sections = abs(on-off); % Divide ‘vector’ Here
VectorCell = mat2cell(vector(vec_nz), 1, sections); % Create Cell
VectorCell{:} % Display Results (Can Be Deleted)
ans =
1 2 3 4
ans =
5 6 7 4 7 8
ans =
1 2 5 4
ans =
5 6
  댓글 수: 2
CarrotCakeIsYum
CarrotCakeIsYum 2015년 9월 28일
Thank you! This was a great help.
Star Strider
Star Strider 2015년 9월 28일
My pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (4개)

Thorsten
Thorsten 2015년 9월 24일
편집: Thorsten 2015년 9월 24일
w = [false v~=0 false]; % "close" v with zeros, and transform to logical
starts = find(w(2:end) & ~w(1:end-1)); % find starts of runs of non-zeros
ends = find(~w(2:end) & w(1:end-1))-1; % find ends of runs of non-zeros
result = arrayfun(@(s,e) v(s:e), starts, ends, 'uniformout', false); % build result
You can also use diff to compute starts and ends indices
starts = find(diff(w) == 1);
ends = find((diff(w) == -1)) - 1;

Stephen23
Stephen23 2015년 9월 24일
편집: Stephen23 2015년 9월 24일
This is fast and simple using accumarray:
V = [1,2,3,4,0,0,0,0,5,6,7,4,7,8,0,0,0,1,2,5,4,0,0,0,0,0,5,6];
X = V>0;
Y = diff([false,X]);
Z = cumsum(Y(X));
out = accumarray(Z(:),V(X),[],@(n){n})

Jos (10584)
Jos (10584) 2015년 9월 24일
% A one-liner, works when vector only contains values as in the example:
vector = [1 2 3 4 0 0 0 0 5 6 7 4 7 8 0 0 0 1 2 5 4 0 0 0 0 0 5 6] ;
OUT = cellfun(@(x) double(x),strsplit(char(vector),char(0)),'un',0) % cellarray

CarrotCakeIsYum
CarrotCakeIsYum 2015년 9월 28일
Thanks everyone - the advice was brilliant and all is working perfectly.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by