MATLAB Answers

Using a for-loop to score values in different intervals

2 views (last 30 days)
Kade Nielsen
Kade Nielsen on 21 Nov 2019
Commented: Kade Nielsen on 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.

  0 Comments

Sign in to comment.

Accepted Answer

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

  1 Comment

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Products