using logical functions to display arrays

5 views (last 30 days)
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.

Accepted Answer

David Hill
David Hill on 1 Apr 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;

More Answers (1)

the cyclist
the cyclist on 1 Apr 2021
Edited: the cyclist on 1 Apr 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

Categories

Find more on Operators and Elementary Operations in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!