How to count the number of times that values changes?

조회 수: 32 (최근 30일)
Mia Dier
Mia Dier 2021년 1월 9일
댓글: Mario Malic 2021년 1월 9일
A=[1 1 1 2 1 3 3 1 1]' I want to get:
B=[NaN 0 0 1 2 3 3 4 4]'
The second and third values of B are 0 because A doesn't change value. Fourth value is 1 because A changes value. Fifth value is 2 because A changes value again. And so on...

채택된 답변

Stephen23
Stephen23 2021년 1월 9일
편집: Stephen23 2021년 1월 9일
A = [1;1;1;2;1;3;3;1;1]
A = 9×1
1 1 1 2 1 3 3 1 1
B = [NaN;cumsum(diff(A)~=0)]
B = 9×1
NaN 0 0 1 2 3 3 4 4

추가 답변 (1개)

Mario Malic
Mario Malic 2021년 1월 9일
편집: Mario Malic 2021년 1월 9일
Hello,
This should do the trick.
B = [NaN; cumsum(diff(A) ~= 0)]';
  댓글 수: 2
Stephen23
Stephen23 2021년 1월 9일
A = [1 1 1 2 1 3 3 1 1]';
B = [NaN, cumsum(diff(A) ~= 0)]'
Error using horzcat
Dimensions of arrays being concatenated are not consistent.
Mario Malic
Mario Malic 2021년 1월 9일
Thanks Stephen, fixed it now.

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

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by