MATLAB: How to make a for loop and use logical operators

for loop

For my college class I have this problem Assign numMatches with the number of elements in userValues that equal matchValue. Ex: If matchValue = 2 and userVals = [2, 2, 1, 2], then numMatches = 3.
My code is
function numMatches = FindValues(userValues, matchValue)
arraySize = 4; % Number of elements in userValues array
numMatches = 0; % Number of elements that equal desired match value
for i = 1:arraySize
if (userValues ~= matchValue)
numMatches = arraySize - i
end
end
end
I also tried
If (userValues == matchValue)
but it did not work I tried with a input of FindValues([2, 2, 1, 2], 2) and it didn't work.
any recommendations

Best Answer

Counting the non-matches is a creative solution to the problem, and it simply requires counting down from the total number of elements. Your code has a few bugs though, such as:
  • you do not increment any counter variable.
  • you forgot to use any indexing to select one element from the input array on each loop iteration.
  • hard-coding the size of the input array.
These are easily fixed:
function numMatches = FindValues(userValues, matchValue)
numMatches = numel(userValues);
for k = 1:numMatches
if userValues(k)~=matchValue
numMatches = numMatches-1
end
end
There are multiple other ways to solve this problem too. One of the simplest would be simply:
nnz(userValues==matchValue)
e.g.
>> nnz([2,2,1,2] == 2)
ans = 3
Related Question