Splitting a vector at sign change
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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 个)
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
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!