Using a for-loop to score values in different intervals

1 vue (au cours des 30 derniers jours)
Kade Nielsen
Kade Nielsen le 21 Nov 2019
Commenté : Kade Nielsen le 21 Nov 2019
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.

Réponse acceptée

darova
darova le 21 Nov 2019
Correct form
if 0 <= x(i) && x(i) < 1

Plus de réponses (0)

Catégories

En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by