How can I count the number of times the value of an array/vector/matrix changes value from x to y?

1 回表示 (過去 30 日間)
For example
Let A = [1;2;1;1;1;3;5;5;5;1;1;1;6;3;4;2;8;6;6;6;6]
How can I determine the number of times the value goes from say 2 to 1, or from 6 to 3 or from 1 to 1 etc. ?
Thank you.

採用された回答

Thorsten
Thorsten 2017 年 3 月 21 日
firstvalue = 2;
nextvalue = 1;
A = A(:); % convert matrix to vector
N = nnz(A(1:end - 1) == firstvalue & A(2:end) == nextvalue);
  3 件のコメント
Ahoora Saadat
Ahoora Saadat 2017 年 3 月 22 日
編集済み: Ahoora Saadat 2017 年 3 月 22 日
So if I wanted this to be done for an n row column vector with possible values going from 1 to m then would the following work:
for i = 1:1:m
fv = i;
for j = 1:1:m
nv = j;
a_i = sum(SA(:) == i) ; % This is the number of times that the system is in state s = i
b_i_j = nnz(SA(1:end - 1) == fv & SA(2:end) == nv); % Where b_i_j is the number of times the system goes from state s = i to state s = j
T_1(i,j) = b_i_j/a_i ; % Where T_1 is the m-by-m transition matrix.
end
end
Thank you again.
Ahoora Saadat
Ahoora Saadat 2017 年 3 月 22 日
Never mind it worked!!! Thank you so much!

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

その他の回答 (0 件)

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by