Different groups of 1s

1 回表示 (過去 30 日間)
AB WAHEED LONE
AB WAHEED LONE 2021 年 3 月 25 日
編集済み: AB WAHEED LONE 2021 年 3 月 31 日
Have been trying to solve this, but couldn't
Any help would be appreciated
I have an array A=[-1 1 -1 -1 -1 -1 1 -1 1 -1 1 -1 -1 -1]
i want to get different groups of 1s like group1 contains ones with length 1 (for consecutive ones), second group contains ones with length 2 ,etc.
same approach for -1s
For 1s output shoud be [ 3 0 0 0 0 0 0 0 0 0 0 0 0 0 ]
For -1s outputs shd be [3 0 1 1 0 0 0 0 0 0 0 0 0 0 ].
  1 件のコメント
Matt J
Matt J 2021 年 3 月 25 日
Why is the output [3 0 0 0 0 0 0,...]? I see 4 groups of length 1 in A.

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

採用された回答

Jan
Jan 2021 年 3 月 25 日
編集済み: Jan 2021 年 3 月 25 日
If speed matters, compile the c file according to the instructions. If the problems are such tiny, it is sufficient to use the M-verion RunLength_M:
A = [-1 1 -1 -1 -1 -1 1 -1 1 -1 1 -1 -1 -1];
value = 1;
[B, N] = RunLength_M(A == value);
Result = histcounts(N(B), 1:numel(A))
% [4 0 0 0 0 0 0 0 0 0 0 0 0 0] not [3 0 0 ...]
value = -1;
[B, N] = RunLength_M(A == value);
Result = histcounts(N(B), 1:numel(A))
% [3 0 1 1 0 0 0 0 0 0 0 0 0 0]
If RunLength_M is still an overkill for you, use:
function [b, n] = RunLengthEnc(x)
d = [true; diff(x(:)) ~= 0]; % TRUE if values change
b = x(d); % Elements without repetitions
k = find([d', true]); % Indices of changes
n = diff(k); % Number of repetitions
end
And if histcounts is too powerful also, a simple loop prodiuces the same result:
function H = myHist(N, Len)
H = zeros(1, Len);
for k = 1:numel(N)
H(N(k)) = H(N(k)) + 1;
end
end
Then the the main code looks like:
A = [-1 1 -1 -1 -1 -1 1 -1 1 -1 1 -1 -1 -1];
value = 1;
[B, N] = RunLengthEnc(A == value);
Result = myHist(N(B), numel(A))
Or with 1 and -1 in the same run:
[B, N] = RunLengthEnc(A);
Result = myHist(N(B == 1), numel(A))
Result = myHist(N(B == -1), numel(A))
  3 件のコメント
Jan
Jan 2021 年 3 月 30 日
Without subfunctions? Then simply copy the code into the main function:
A = [-1 1 -1 -1 -1 -1 1 -1 1 -1 1 -1 -1 -1];
d = [true; diff(x(:)) ~= 0]; % TRUE if values change
b = x(d); % Elements without repetitions
k = find([d', true]); % Indices of changes
n = diff(k); % Number of repetitions
Result = histcounts(n(b == 1), 1:numel(A))
Result = histcounts(n(b == -1), 1:numel(A))
AB WAHEED LONE
AB WAHEED LONE 2021 年 3 月 31 日
編集済み: AB WAHEED LONE 2021 年 3 月 31 日
This seems shortest one,,Got it ,thank You

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

その他の回答 (1 件)

Matt J
Matt J 2021 年 3 月 25 日
編集済み: Matt J 2021 年 3 月 29 日
Using the tools in this File Exchange submission,
A=[-1 1 -1 -1 -1 -1 1 -1 1 -1 1 -1 -1 -1];
map=(A==-1);
L=groupFcn(@sum, map, groupTrue(map));
output=histcounts(L,1:numel(A)+1)
output = 1×14
3 0 1 1 0 0 0 0 0 0 0 0 0 0

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by