필터 지우기
필터 지우기

i am not getting what is the problem with it

조회 수: 3 (최근 30일)
RITISH
RITISH 2022년 12월 16일
편집: Torsten 2022년 12월 16일
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