Effacer les filtres
Effacer les filtres

i am not getting what is the problem with it

3 vues (au cours des 30 derniers jours)
RITISH
RITISH le 16 Déc 2022
Modifié(e) : Torsten le 16 Déc 2022
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.

Réponses (2)

Voss
Voss le 16 Déc 2022
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 commentaires
RITISH
RITISH le 16 Déc 2022
So what can be used in this case to get the output with the "if" statement
Voss
Voss le 16 Déc 2022
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

Connectez-vous pour commenter.


Torsten
Torsten le 16 Déc 2022
Modifié(e) : Torsten le 16 Déc 2022
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)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by