How do I make a for loop and use logical operators

조회 수: 17 (최근 30일)
Quentin MckNight
Quentin MckNight 2017년 11월 17일
댓글: Quentin MckNight 2017년 11월 20일
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

채택된 답변

Stephen23
Stephen23 2017년 11월 17일
편집: Stephen23 2017년 11월 17일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Multirate Signal Processing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by