Error check if statement
3 views (last 30 days)
Show older comments
Hi all,
I am trying to create a program to calculate resistor values from the colour code. The calculations work but I tried to input an error checking step to ensure that only valid colours are input by the user. For some reason it dosen't work as I expected. I have defined the values of the resistors at the beginning as individual variables then tried to create an if statement that would check that only a valid colour is input later on. Can anyone see where I went wrong??
Thanks
black = 0;
brown = 1;
red = 2;
orange = 3;
yellow = 4;
green = 5;
blue = 6;
violet = 7;
grey = 8;
white = 9;
gold = 5;
silver = 10;
%Request number of bands on the resistor from User
x=input('No of bands = ');
% If 4 BAND resistor use following code block
if x==4
%Input colours of each band of the resistor
k = input('band 1 colour = ');
l = input('band 2 colour = ');
m = input('band 3 colour = ');
n = input('band 4 colour = ');
if k ~= black||brown||red||orange||yellow||green||blue||violet||grey||white
disp('Incorrect Colour for Band 1')
elseif l ~= black||brown||red||orange||yellow||green||blue||violet||grey||white
disp('Incorrect Colour for Band 2')
elseif m ~= black||brown||red||orange||yellow||green||blue||violet||grey||white||gold||silver
disp('Incorrect Colour for Band 3')
elseif n ~= brown||red||gold||silver
disp('Incorrect Colour for Band 4')
else
end
o = k*10 + l;
p = o * 10^m;
disp ('resistor value (ohms) = '); disp(p);
if n == red||brown||gold||silver
disp('tolerence (+/-) % = '); disp(n);
else
disp('incorrect input')
end
0 Comments
Answers (2)
Star Strider
on 15 Sep 2016
I would replace your tests with this ‘test’ function and calls to it.
Example:
test = @(k) ismember(k,{'black','brown','red','orange','yellow','green','blue','violet','grey','white'});
k = 'red'
Out1 = test(k)
k = 'indigo'
Out2 = test(k)
k =
red
Out1 =
1
k =
indigo
Out2 =
0
That should also make your code more efficient.
0 Comments
Walter Roberson
on 15 Sep 2016
k ~= black||brown||red||orange||yellow||green||blue||violet||grey||white
means the same thing as
(k ~= black) || (brown ~= 0) || (red ~= 0) || (orange ~= 0) || (yellow ~= 0) || (green ~= 0) || (blue ~= 0) || (violet ~= 0) || (grey ~= 0) || (white ~= 0)
which is of course always true since brown ~= 0
I have been unsuccessful in finding any computer languages which "distribute" relational operators in the way you thought MATLAB worked, so I have yet to figure out where people are picking up the idea that it could work.
I suggest that you consider using ismember()
0 Comments
See Also
Categories
Find more on Blue 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!