Undefined function 'piecewise' for input arguments of type 'double'.
Show older comments
I am trying to loop through data and find the max profit. Please help!
qh=@(p) piecewise(p<=100, 50, (100<=p)&&(p<=200), 100-(p/2),p>=200, 0);
qa=@(p) piecewise(p<=150,50-(p/3),p>=150,0);
revenue=@(p) p*(qh(p)+qa(p));
cost=@(p) -2000-(20*(qh(p)+qa(p)));
z=FindMaxPrice;
function maxPro=FindMaxPrice(qh,qa)
maxPro=0;
for p=0:1:202
profit=@(p) (p - 20)*qh(p) + (p - 20)*qa(p) - 2000;
if profit(p)>maxPro
maxPro=profit(p);
end
end
maxPro
end
6 Comments
Haley Palmer
on 23 Apr 2020
Haley Palmer
on 23 Apr 2020
Haley Palmer
on 23 Apr 2020
"Unless that is not what you meant"
If you are not sure if p is symbolic, then it probably isn't. A variable is symbolic if it is declared with sym or syms, and allows the use of the functions and methods provided in the Symbolic Toolbox:
As I wrote in my earlier comment, the function piecewise is part of that toolbox. You cannot simply use piecewise on some numeric variable that you have defined (the piecewise documentation makes it very clear that at a bare minimum its conditions must be symbolic).
"I am not doing it with basic operations because I am trying to substite p in in the function to find the max profit value"
I don't see why that requires symbolic variables: basic MATLAB numeric operations, functions, and/or indexing would probably do everything you need. You should read about logical indexing, and probably do the intrductory tutorials:
Haley Palmer
on 23 Apr 2020
Answers (1)
Star Strider
on 23 Apr 2020
Note that you can easily convert your piecewise symbollic expressions to appropriate numerical expressions.
So ‘qh’ and ‘qa’ become respectively:
qh=@(p) (p<=100).*50 + ((100<=p)&(p<=200)).*100-(p/2) + (p>=200).*0;
qa=@(p) (p<=150).*50-(p/3) + (p>=150).*0;
The element-wise operation (.*) isn’t always necessary. I use it in expressions such as these because it’s better to do it than not, in the event the sub-expression is a function of the argument variable (here ‘p’).
The easiest way to check to be certain these do what you want them to is to plot them:
g = linspace(0, 300, 100);
figure
plot(g, qh(g), g, qa(g))
grid
.
Categories
Find more on Loops and Conditional Statements 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!