Mesh/Surf plot of function with if statements

3 ビュー (過去 30 日間)
Morten Hansen
Morten Hansen 2019 年 8 月 3 日
コメント済み: Star Strider 2019 年 8 月 3 日
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 日
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 件のコメント
Morten Hansen
Morten Hansen 2019 年 8 月 3 日
Thanks Star Strider for the suggusted code and the explanation regarding 'logical indexing'
Star Strider
Star Strider 2019 年 8 月 3 日
As always, my pleasure.
To see how it works, plot ‘Z1’ and ‘Z2’ separately.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSurface and Mesh Plots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by