필터 지우기
필터 지우기

Determine the number of elements in succession in a vector that are equal in a succinct way

조회 수: 1 (최근 30일)
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?

채택된 답변

Bruno Luong
Bruno Luong 2022년 11월 15일
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]
x = 1×25
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'))
ans = 7
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
  댓글 수: 1
David Haydock
David Haydock 2022년 11월 15일
You have no idea how much help this function is to me. It makes all of my code so much more streamlined. Thank you so much!

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by