Switch Case when a value stagnates
3 views (last 30 days)
Show older comments
Suppose I have a switch case scenario and a variable, var which records a value from a for-loop as such:
1st loop: var=10
2nd loop: var=9
3rd loop: var=9
4th loop: var=8
5th loop: var=8
6th loop: var=8
7th loop: var=8
8th loop: var=8
9th loop: var=8
When any value (in this case 8) is repeated for 3 times, I need to switch from case 1 to case 2. Now the question is, how can I check if a value is repeated 3 times?
In the case above, the first switch is performed when the value 8 is repeated 3 times (4th-6th iteration); and the second switch is performed the next series of value 8 is repeated for 3 times (7th-9th iteration).
0 Comments
Accepted Answer
Ben11
on 23 Jun 2014
Edited: Ben11
on 23 Jun 2014
Here is a simple solution to detect the first occurence of values repeated 3 times; you could customize it to be more general.
clear all clc
A = [2 6 8 2 8 8 3 2 9 8 8 11 12 18 17 18 18 18 15 3];% Create a dummy vector
CheckSimilar = 0;
for i = 2:length(A)
if A(i) == A(i-1)
CheckSimilar = CheckSimilar +1;
end
if CheckSimilar == 3
fprintf('The value %i is repeated %i times',A(i),CheckSimilar);
return
end
end
0 Comments
More Answers (0)
See Also
Categories
Find more on Function Handles in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!