Determine the number of elements in succession in a vector that are equal in a succinct way
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
David Haydock
il 15 Nov 2022
Commentato: David Haydock
il 15 Nov 2022
I have a sequence, say:
x = [4 4 4 4 4 1 1 1 1 1 1 2 2 2 2 2 2 2 4 4 4 4 4 4 4];
I need to get the 4's at the end of the sequence, and count how many of them occur in a row. I can't simply do the sum of 4's that are occurring in x, because there are 4's earlier on in the sequence. Is there a function, or succinct way of doing this that doesn't require looping through the whole vector?
Risposta accettata
Bruno Luong
il 15 Nov 2022
You can use many runlength in filesubmission. I use here my own;
x = [4 4 4 4 4 1 1 1 1 1 1 2 2 2 2 2 2 2 4 4 4 4 4 4 4]
[len, v] = runlengthencoder(x);
len(find(v==4,1,'last'))
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 x n) integer, group number (value in 1:m)
% 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
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Bessel functions in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!