Finding cluster of positive and negative numbers in an array, then the maximum and minimum value in each cluster

조회 수: 5 (최근 30일)
Say for example, I have
a = [ 2 -2 1 4 5 -3 -2 1 -1 2 5 -2 6 -7 1 3 -4]
What I want is to group the elements as
[2], [-2], [1 4 5], [-3 -2], [1], [-1], [2 5], [-2], [6], [-7], [1, 3], [-4]
Next, I want to do this
[2], [-2], [5], [-3], [1], [-1], [5], [-2], [6], [-7], [3], [-4]
Finally I want to extract index position of these values in the original array aa.
[1 2 5 6 8 9 11 12 13 14 16 18]
How do I vectorize this process?

답변 (1개)

Bruno Luong
Bruno Luong 2022년 10월 31일
편집: Bruno Luong 2022년 10월 31일
NOTE: max of [-3 -2] is -2 not -3. Your array has 17 elements, cannot have element index of 18.
a = [ 2 -2 1 4 5 -3 -2 1 -1 2 5 -2 6 -7 1 3 -4];
lgt = runlengthencoder(a > 0);
c = mat2cell(a, 1, lgt);
[maxa, subidx]=cellfun(@max, c)
maxa = 1×12
2 -2 5 -2 1 -1 5 -2 6 -7 3 -4
subidx = 1×12
1 1 3 2 1 1 2 1 1 1 2 1
idx=cumsum([0, lgt(1:end-1)])+subidx
idx = 1×12
1 2 5 7 8 9 11 12 13 14 16 17
% Do the same thinh with min
...
function [len, v, gr, subidx] = runlengthencoder(X)
% [len, v, gr, subidx] = runlengthencoder(X)
% Run-length encoder
%
% INPUT
% X is (1 x n) row vector, column is also allowed
% OUTPUTS:
% len: integer arrays (1 x m)
% v: (1 x m) ordering subset of X, such that two adjadcent elements are differents
% and X = replelem(v, len)
% gr: 1:m (group number)
% subidx: (1 x n) integer, interior indexes of X with in the group
%
% See also: runlengthdecoder
if ~isrow(X)
X = reshape(X, 1, []);
end
n = size(X,2);
if n > 0
b = [true, diff(X)~=0];
ij = find([b, true]);
len = diff(ij);
v = X(b);
if nargout >= 3
gr = repelem(1:length(len),len);
if nargout >= 4
subidx = ones(1,n);
subidx(ij(2:end-1)) = 1-len(1:end-1);
subidx = cumsum(subidx, 2);
end
end
else
[len, v, gr, subidx] = deal([]);
end
end % runlengthencoder

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by