MATLAB Answers

setting a threshold for consecutive number

3 views (last 30 days)
Hello everybody, I have a problem with this following issue:
I want to select X=1 or 2 randomly but if in this code if X=2
happens 3 times consecutively ,for the next time, program should select X=1 and vice versa.
(I mean 1 or 2 should be selected randomly but with a threshold==3 after that it should choice another value)
my code is here:
Please if you know it tell me about that, I really stuck (Thanks in advance)
Z{1,1}={0};
for h=1: 45
Y = {'L', 'R'};
%% Here is my problem (Setting a threshold)
X = randi([1, 2], 1); % Get a 1 or 2 randomly.but I want to set a threshold that if X=2 happens 3 times consecutively for the next time choice another value and vice versa. (I mean (for example) it should not select X=2, 4 times consecutively in this loop randomly )
Z{1,h} = Y(X);
end

Accepted Answer

Image Analyst
Image Analyst on 17 Sep 2021
Make X an array, and if X(h), X(h-1) and X(h-2) are all the same, get a new X. Like this:
numTrials = 45;
maxRunLength = 3;
Z{1}={0};
Y = {'L', 'R'};
for h = 1 : numTrials
% Here is my problem (Setting a threshold)
X(h) = randi([1, 2], 1); % Get a 1 or 2 randomly.but I want to set a threshold that if X=2 happens 3 times consecutively for the next time choice another value and vice versa. (I mean (for example) it should not select X=2, 4 times consecutively in this loop randomly )
if h >= maxRunLength
theRange = range(X(h-maxRunLength+1 : h))
if theRange == 0
% They're all the same. Swap the current X so 1 is now 2 or 2 is now 1
X(h) = 3 - X(h);
end
end
Z(h) = Y(X(h)); % Use parentheses, not braces.
end
% Show values in command window
X
Z
You'll see
X =
Columns 1 through 22
1 2 1 1 2 1 2 1 2 1 2 1 1 2 2 1 2 2 1 1 2 1
Columns 23 through 44
1 2 1 1 2 1 1 2 2 1 1 2 1 2 1 1 2 2 1 2 1 1
Column 45
2
Z =
1×45 cell array
Columns 1 through 15
{'L'} {'R'} {'L'} {'L'} {'R'} {'L'} {'R'} {'L'} {'R'} {'L'} {'R'} {'L'} {'L'} {'R'} {'R'}
Columns 16 through 30
{'L'} {'R'} {'R'} {'L'} {'L'} {'R'} {'L'} {'L'} {'R'} {'L'} {'L'} {'R'} {'L'} {'L'} {'R'}
Columns 31 through 45
{'R'} {'L'} {'L'} {'R'} {'L'} {'R'} {'L'} {'L'} {'R'} {'R'} {'L'} {'R'} {'L'} {'L'} {'R'}
  1 Comment
mohadeseh zamani
mohadeseh zamani on 18 Sep 2021
you're right. Thanks a zillion,you really helped me.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by