Mesh/Surf plot of function with if statements
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Morten Hansen
il 3 Ago 2019
Commentato: Star Strider
il 3 Ago 2019
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 Commenti
Risposta accettata
Star Strider
il 3 Ago 2019
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 Commenti
Star Strider
il 3 Ago 2019
As always, my pleasure.
To see how it works, plot ‘Z1’ and ‘Z2’ separately.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Surface and Mesh Plots in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!