For loop in if/elseif statements which compares multiple characters
Show older comments
I have a project with school, in which I have to make a script in which I can plot possible darttrows on a dartboard. I have already found a way to plot it, As a small example, here below. The problem is that a dart board has 62 different scores and I have to emulate when someone wants to trow 1 time, 2 time or 3 time. Which means that the loop can take for over 372 comparisons. Can I use For loops for this to shorten the script.
if trows == 1
if (t1 == p1)% The t1 is already asked. They will answer in a dartscore, for example Bulleye is B and triple 20 is T20, P1 is the position of the score, in this case it is single 1, thus S1)
p1x = [458];
p1y = [429 354];
plot(p1x, p1y, 'b*', 'LineWidth', 2, 'MarkerSize', 15)
elseif (t1 == p2)
p2x = [428];
p2y = [429 354];
plot(p2x, p2y, 'b*', 'LineWidth', 2, 'MarkerSize', 15)
elseif (t1 == p3)
p3x = [458];
p3y = [429 354];
plot(p3x, p3y, 'b*', 'LineWidth', 2, 'MarkerSize', 15)
elseif (t1 == p4)
p4x = [458];
p4y = [429 354];
plot(p4x, p4y, 'b*', 'LineWidth', 2, 'MarkerSize', 15)
4 Comments
Walter Roberson
on 24 Mar 2019
How does that differ from
if t1 == p1 || t1 == p2 || t1 == p3 || t1 == p4
x = 458;
y = 4219 354;
plot(x, y, 'b*', 'LineWidth', 2, 'MarkerSize', 15)
end
Was that difference between 458 (p1, p3, p4) and 428 (p2) significant?
Question: what datatype is t1 ? What datatype are p1, p2, p3, etc. ?
Selsa31
on 24 Mar 2019
Selsa31
on 24 Mar 2019
Walter Roberson
on 24 Mar 2019
I suggest you input the values as character vector, such as if you use
%sector 1: bull's eye 'e'
%sector 2: bull 'b'
%sector 3: single (inner) 's or 'p'
%sector 4: triple 't'
%sector 5: single (outer) 's' or 'p'
%sector 6: double 'd'
t1 = input('enter first throw: ', 's');
Then
if isempty(t1)
error
end
%default is single if the user only inputs a number
if ~ismember(lower(t1(1)), ['1':'9', 'sdtpbe'])
error
end
if rand < 1/3
sector = 3;
else
sector = 5;
end
if ismember(lower(t1(1)), 'sp') %'s', and 'p' is alias for it
t1 = t1(2:end);
elseif ismember(lower(t1(1)), 'd')
sector = 6;
t1 = t1(2:end);
elseif ismember(lower(t1(1)), 't')
sector = 4;
t1 = t1(2:end)
elseif ... take care of bull and bull's eye
end
%now sector is set appropriately and t1 has characters representing a number, or possibly empty for 'b' (bull) or 'e' (bulls eye)
Accepted Answer
More Answers (0)
Categories
Find more on MATLAB 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!