MATLAB Answers

Counting how many times a number occured after a specific number

1 ビュー (過去 30 日間)
Chad
Chad 2020 年 4 月 10 日
コメント済み: Kelly Kearney 2020 年 4 月 10 日
Lets say I have a sequence of numbers ranging from 1 to 4, S = [ 3 2 2 4 3 1 ]. I want a 4x4 matrix which tells me how many times I went from say 3 to 2 or 4 to 1. It would look like this: M = [ 0 0 0 0; 0 1 0 1; 1 1 0 0; 0 0 1 0]. Sounds simple, but I'm out of thoughts. Thanks.
  1 件のコメント
darova
darova 2020 年 4 月 10 日
Can you explain more? I don't understand

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

採用された回答

Kelly Kearney
Kelly Kearney 2020 年 4 月 10 日
This is a good use case for accumarray:
S = [ 3 2 2 4 3 1];
[seq, ~, g] = unique([S(1:end-1)' S(2:end)'], 'rows');
n = accumarray(g, ones(size(g)));
M = zeros(4);
idx = sub2ind(size(M), seq(:,1), seq(:,2));
M(idx) = n;
  3 件のコメント
Kelly Kearney
Kelly Kearney 2020 年 4 月 10 日
Though apparently the call to unique is unnecessary... possibly what you were suggesting?
S = [ 3 2 2 4 3 1 3 2];
accumarray([S(1:end-1)' S(2:end)'], 1)
ans =
0 0 1 0
0 1 0 1
1 2 0 0
0 0 1 0
I learned something new!

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

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2020 年 4 月 10 日
accumarray(hankel(S(1:end-1),S(end-1:end)),1)

Community Treasure Hunt

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

Start Hunting!

Translated by