using logical functions to display arrays

5 次查看(过去 30 天)
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.

采纳的回答

David Hill
David Hill 2021-4-1
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;

更多回答(1 个)

the cyclist
the cyclist 2021-4-1
编辑:the cyclist 2021-4-1
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

类别

Help CenterFile Exchange 中查找有关 Operators and Elementary Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by