Mesh/Surf plot of function with if statements
1 次查看(过去 30 天)
显示 更早的评论
I’m trying to plot the following function (cost curve), basically combining two functions in a plot separated by an upper bound:

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.
0 个评论
采纳的回答
Star Strider
2019-8-3
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Surface and Mesh Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!