i am not getting what is the problem with it

3 次查看(过去 30 天)
Given three input variables:
  • hotels - a list of hotel names
  • ratings - their ratings in a city
  • cutoff - the rating at which you would like to cut off
return only the names of those hotels with a rating of cutoff value or above as a column vector of strings good.
So this is one of the question from cody.I tried it like this-
function good = find_good_hotels(hotels,ratings,cutoff)
if ratings>=cutoff
Ridx=find(ratings)
good=hotels(Ridx)
end
but it said the code ran without an output.
but when i ran with this folloowing code it worked.
function good = find_good_hotels(hotels,ratings,cutoff)
Ridx=find(ratings>=cutoff)
good=hotels(Ridx)
end
Isnt both code similar? The former one with "if" should run also right.Or please clear me out where i am getting wrong.

回答(2 个)

Voss
Voss 2022-12-16
function good = find_good_hotels(hotels,ratings,cutoff)
if ratings>=cutoff
Ridx=find(ratings)
good=hotels(Ridx)
else
% if ratings < cutoff, then "good" is undefined, so no output is produced
end
  2 个评论
RITISH
RITISH 2022-12-16
So what can be used in this case to get the output with the "if" statement
Voss
Voss 2022-12-16
If you want to use the "if" statement approach, you'll also need a for loop, since ratings is a vector.
It's better to use a logical indexing approach:
function good = find_good_hotels(hotels,ratings,cutoff)
good=hotels(ratings>=cutoff);
end
which is even simpler than the find approach.
But here's the "if" approach:
function good = find_good_hotels(hotels,ratings,cutoff)
good = strings(0,1);
for ii = 1:numel(hotels)
if ratings(ii) >= cutoff
good(end+1,1) = hotels(ii);
end
end
end

请先登录,再进行评论。


Torsten
Torsten 2022-12-16
编辑:Torsten 2022-12-16
function good = find_good_hotels(hotels,ratings,cutoff)
if ratings>=cutoff
Ridx=find(ratings)
good=hotels(Ridx)
end
end
The if-statement does not make sense. The inner of the if-statement is executed only if for all components i of the array ratings, the condition ratings(i)>=cutoff is satisfied. In this case, the indices of the nonzero elements of "ratings" are written in Ridx which also makes no sense because they have to be compared to the value "cutoff".
The easiest solution is simply
good = hotels(ratings>=cutoff)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by