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

4 ビュー (過去 30 日間)
David Haydock 2022 年 11 月 15 日
コメント済み: David Haydock 2022 年 11 月 15 日
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?
##### 1 件のコメント-1 件の古いコメントを表示-1 件の古いコメントを非表示
David Haydock 2022 年 11 月 15 日
edited the question to say "in succession" instead of "in a row" to not confuse

サインインしてコメントする。

### 採用された回答

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
%
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 件のコメント-1 件の古いコメントを表示-1 件の古いコメントを非表示
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!

サインインしてコメントする。

### カテゴリ

Help Center および File ExchangeBessel functions についてさらに検索

### Community Treasure Hunt

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

Start Hunting!

Translated by