MATLAB: How to use a If and Else statement to see if a value is within a matrix

if statement

Hello,
This is my first time using this forum, so I though it would be great to ask the community to help me with a homework problem I have to do. The question I have is how can I use an If and Else statement to see if a value I have in a matrix is within a matrix? I attached a picture of the homework problem if you want clarity of what I had to do
. I did the code for the problem, but I'm getting errors when doing it.
Any help with be appreciable.
Here's the code I have so far:
parttolerance = [23.45 27.89 44.203 9.8 10.3];
save parttol.dat parttolerance -ascii
partweight = input('Please enter the weight of a part: ');
PartWeight = tolerance(partweight);
disp(PartWeight);
function PartWeight = tolerance(partweight)
if partweight == parttolerance(:)
PartWeight= 'The weight you entered is within the range';
else
PartWeight = 'The weight you entered is not within the range';
end
end
%{
Here's the error I get from the code once I run it
Error in parttol>tolerance (line 11)
if partweight == parttolerance(:)
Error in parttol (line 6)
PartWeight = tolerance(partweight);
%}

Best Answer

First, if you are writing this code in a script file, then the variable parttolerance is not visible inside the function tolerance. You need to pass it as input to the function.
Change the line
function PartWeight = tolerance(partweight)
to
function PartWeight = tolerance(partweight, parttolerance)
also change the line
PartWeight = tolerance(partweight);
to
PartWeight = tolerance(partweight, parttolerance);
Second, the condition
partweight == parttolerance(:)
is not doing what you might think it does. The correct way to check if an element is a part of a matrix is to use ismember function
ismember(partweight, parttolerance)
Related Question