using logical functions to display arrays

5 visualizaciones (últimos 30 días)
Ibrahim Alsaif
Ibrahim Alsaif el 1 de Abr. de 2021
Comentada: Ibrahim Alsaif el 1 de Abr. de 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.

Respuesta aceptada

David Hill
David Hill el 1 de Abr. de 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;

Más respuestas (1)

the cyclist
the cyclist el 1 de Abr. de 2021
Editada: the cyclist el 1 de Abr. de 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

Categorías

Más información sobre Operators and Elementary Operations en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by