Mesh/Surf plot of function with if statements

I’m trying to plot the following function (cost curve), basically combining two functions in a plot separated by an upper bound:
Example.PNG
However, I can’t get the if statements working properly – the functions are not combining correctly in the plot.
It’s my code so far:
[X,Y] = meshgrid(0:1:20); %Evaluates the function between 0 and 20 in both x and y. Interval set at 1.
if 4*X.^2+3*Y.^2<=225
Z = 2*sqrt(100*X.^2+75*Y.^2); %Conditionally Function (1)
else
Z = 75+4/3*X.^2+Y.^2; %Conditionally Function (2)
end
figure(1); %Allows working with multiple figures simultaneously
mesh(X,Y,Z) %mesh plot
colorbar %add colorbar in plot
xlabel('Output, q_{2}','FontSize',8,'FontWeight','normal','Color','k') %label x-axis
ylabel('Output, q_{1}','FontSize',8,'FontWeight','normal','Color','k') %label y-axis
zlabel('Cost, C(q;P)','FontSize',8,'FontWeight','normal','Color','k') %label z-axis
figure(2); %Next figure
surf(X,Y,Z) %surface plot
colorbar %add colorbar in plot
xlabel('Output, q_{2}','FontSize',8,'FontWeight','normal','Color','k') %label x-axis
ylabel('Output, q_{1}','FontSize',8,'FontWeight','normal','Color','k') %label y-axis
zlabel('Cost, C(q;P)','FontSize',8,'FontWeight','normal','Color','k') %label z-axis
I have also looked at conditionally defined expression or function using piecewise but couldn’t get it to work either.
Please could someone offer corrected code or suggestions for changes?
Many thanks in advance.

 채택된 답변

Star Strider
Star Strider 2019년 8월 3일

0 개 추천

Try this:
Z1 = (2*sqrt(100*X.^2+75*Y.^2)).*((4*X.^2+3*Y.^2)<=225);
Z2 = (75+4/3*X.^2+Y.^2).*((4*X.^2+3*Y.^2)>225);
Z = Z1 + Z2;
It creates a logical matrix separately with ‘((4*X.^2+3*Y.^2)<=225)’ and ‘((4*X.^2+3*Y.^2)>225)’ that then become numeric matrices with (0,1) elements when used in the calculations of ‘Z1’ and ‘Z2’. These are then added to form ‘Z’. Unfortunately, ‘logical indexing’ will not otherwise work here, because the logical operations will create logical vectors, destroying the matrix structure.

댓글 수: 2

Thanks Star Strider for the suggusted code and the explanation regarding 'logical indexing'
As always, my pleasure.
To see how it works, plot ‘Z1’ and ‘Z2’ separately.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Line Plots에 대해 자세히 알아보기

질문:

2019년 8월 3일

댓글:

2019년 8월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by