필터 지우기
필터 지우기

Splitting a vector at sign change

조회 수: 9 (최근 30일)
Holmbrero
Holmbrero 2020년 6월 8일
댓글: Holmbrero 2020년 6월 9일
Hi!
I have a vector with values > 0 and values < 0 such as for example:
K = [1 2 3 4 5 6 7 8 -1 -2 -3 -4 -5 -6 -7 -8 1 2 3 4 5 6 7 8] and so on....
I want to split this vector to n new vectors where the sign changes from + to - and vice versa such that:
N1 = [1 2 3 4 5 6 7 8]
N2 = [-1 -2 -3 -4 -5 -6 -7 -8]
N3 = [1 2 3 4 5 6 7 8]
The K vector does not have a set number of positive or negative values between each sign change.
Any suggestions?
Regards

채택된 답변

KSSV
KSSV 2020년 6월 8일
편집: KSSV 2020년 6월 8일
K = [1 2 3 4 5 6 7 8 -1 -2 -3 -4 -5 -6 -7 -8 1 2 3 4 5 6 7 8] ;
K = K' ;
S = sign(K) ;
C = mat2cell(S, diff([0; find(diff(S)); size(S,1)]));
L = cellfun(@numel,C) ;
iwant = mat2cell(K,L) ;
celldisp(iwant)
  댓글 수: 2
Stephen23
Stephen23 2020년 6월 8일
편집: Stephen23 2020년 6월 8일
A simpler and more efficient approach to get the run lengths:
>> L = diff(find([1,diff(sign(K)),1]))
L =
8 8 8
Holmbrero
Holmbrero 2020년 6월 9일
Thanks for the input!
I have a follow up question.
I want the values from iwant as a txt. or equal with each cell as a column such that:
iwant(1) iwant(2) iwant(3)
1 -1 1
2 -2 2
3 -3 3
4 -4 4
5 -5 5
6 -6 6
7 -7 7
8 -8 8
And so on. Any suggestions?
Regards,

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

추가 답변 (2개)

Holmbrero
Holmbrero 2020년 6월 8일
Works great. Thank you very much!

Kevin Joshi
Kevin Joshi 2020년 6월 8일
K = [1 2 3 ...
-1 -2 -3 ...
-1 -2 -3 -4 ...
1 2 3 4 5 6 7 8];
%%
m = 1;
n = 1;
x = 1;
y = 1;
for i = 1:length(K)
if K(i)<0
s.(['n' num2str(m)])(n) = K(i);
n = n + 1;
if (i+1) < length(K) && K(i+1) > 0
x = x + 1;
y = 1;
end
else
s.(['p' num2str(x)])(y) = K(i);
y = y + 1;
if (i+1) < length(K) && K(i+1) < 0
m = m + 1;
n = 1;
end
end
end

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by