Using a for-loop to score values in different intervals

조회 수: 1 (최근 30일)
Kade Nielsen
Kade Nielsen 2019년 11월 21일
댓글: Kade Nielsen 2019년 11월 21일
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