- 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.
How do I make a for loop and use logical operators
13 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Quentin MckNight
am 17 Nov. 2017
Kommentiert: Quentin MckNight
am 20 Nov. 2017
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
0 Kommentare
Akzeptierte Antwort
Stephen23
am 17 Nov. 2017
Bearbeitet: Stephen23
am 17 Nov. 2017
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:
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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Multirate Signal Processing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!