I want to double numbers that are less than the given parameter. What do I need to change

16 次查看(过去 30 天)
function dataSamples = AdjustMinValue(numberSamples, userSamples, minValue)
% numberSamples: Number of data samples in array dataSamples
% userSamples : User defined array
% minValue : Minimum value of any element in array
% Write a for loop that iterates from 1 to numberSamples to double any element's
% value in dataSamples that is less than minValue
for i = 1:numberSamples
if userSamples(i) > minValue
dataSamples = userSamples * 2
end
end
end
This code doubles all user samples. It should only double numbers less minValue.
Ex.) if minValue = 10 then dataSamples [2,12,9,20] becomes [4,12,18,20]

回答(1 个)

Giuseppe Inghilterra
编辑:Giuseppe Inghilterra 2020-2-22
Your function will be:
function dataSamples = AdjustMinValue(numberSamples, userSamples, minValue)
% numberSamples: Number of data samples in array dataSamples
% userSamples : User defined array
% minValue : Minimum value of any element in array
% Write a for loop that iterates from 1 to numberSamples to double any element's
% value in dataSamples that is less than minValue
for i = 1:numberSamples
if userSamples(i) > minValue
dataSamples(i) = userSamples(i);
else
dataSamples(i) = userSamples(i)*2;
end
end
end
However, you don't need a for loop, you can just run following one-line code based on your last example:
dataSamples(dataSamples<minValue) = dataSamples(dataSamples<minValue)*2;
If we applied to your function, it becomes:
function dataSamples = AdjustMinValue(numberSamples, userSamples, minValue)
dataSamples = userSamples;
dataSamples(dataSamples<minValue) = dataSamples(dataSamples<minValue)*2;
end

Community Treasure Hunt

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

Start Hunting!

Translated by