Using a for-loop to score values in different intervals

1 次查看(过去 30 天)
I need to use a for-loop (for a class, so we have to use the loop to do this) to find the score for the values of some vector 'x', which is a 30x1 vector containing values ranging from 0 to 6. These values are not integers. We are asked to produce a vector (I'll refer to it as 'y' here) with the 'scores' assigned, and the intervals and values for each score were provided as follows:
[0,1), score = 4
[1,2), score = 2
[2,3), score = 1
[3,5), score = 0
> 5, score = -5
I decided to write the following code to try and find a 30x1 vector with the score for each individual value of 'x':
for i = 1:30
if 0 <= x(i) < 1
y(i) = 4;
elseif 1 <= x(i) < 2
y(i) = 2;
elseif 2 <= x(i) < 3
y(i) = 1;
elseif 3 <= x(i) < 5
y(i) = 0;
else
y(i) = -5;
end
end
However, after running this code with my 'x' vector, the output ('y') was a 30x1 vector containing a value of 2 for each number.
I double checked the x-values, and they did not all fall within the [1,2) interval, so I expected the score to differ throughout 'y'.
Any help or advice would be appreciated, especially if the way I decided to go about it was inefficient. I'm always open to new solutions or corrections to my attempt.
Thanks.

采纳的回答

darova
darova 2019-11-21
Correct form
if 0 <= x(i) && x(i) < 1

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by