using logical functions to display arrays

5 vues (au cours des 30 derniers jours)
Ibrahim Alsaif
Ibrahim Alsaif le 1 Avr 2021
Hello , I have an inquiry about a question that I am trying to solve:
I have tried solving it through making an M-file function named discount then making the following function:
function d=discount(x)
if x<10
d=0.95.*x;
elseif x>=10 & x<=30
d=0.85.*x;
elseif x>30
d=0.8.*x;
end
when I try calling the function in another file (after saving the previous function) and using P as an input:
P =[12 7.95 88 26.5 27.9 3.5 57 65.9 17.7 35.6 15 96.5 ]
discount(P)
I do not get any results!
I think the problem has to do with P consisting of numbers that undergo more than one condition but I still do not know the proper solution.

Réponse acceptée

David Hill
David Hill le 1 Avr 2021
P =[12 7.95 88 26.5 27.9 3.5 57 65.9 17.7 35.6 15 96.5 ];
discountedPrice=zeros(size(P));
discountedPrice(P<10)=P(P<10)*.95;
discountedPrice(P>=10&P<=30)=P(P>=10&P<=30)*.85;
discountedPrice(P>30)=P(P>30)*.8;

Plus de réponses (1)

the cyclist
the cyclist le 1 Avr 2021
Modifié(e) : the cyclist le 1 Avr 2021
When x is a vector, then
if x < 10
is interpreted as "if all elements of x are less than 10". Your if statement is never entered.
You either need to use a for loop over x, or just use
x < 10

Catégories

En savoir plus sur Operators and Elementary Operations dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by