using logical functions to display arrays

조회 수: 1 (최근 30일)
Ibrahim Alsaif
Ibrahim Alsaif 2021년 4월 1일
댓글: Ibrahim Alsaif 2021년 4월 1일
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