How to plot multiple curves in a single figure by varying a parameter?

3 views (last 30 days)
I have the following equation :-
my x ranges from (-5,10).
I want to plot multiple curves (y vs x) of the following equation by varying the parameter 'c' i.e giving some discrete values of 'c'.
How do I do that using a for loop?

Accepted Answer

Star Strider
Star Strider on 13 Aug 2021
Edited: Star Strider on 13 Aug 2021
No loop required.
Try this —
syms c x y
Eqn = y^2/2-cos(x) == c
Eqn = 
y = solve(Eqn,y)
y = 
yfcn = matlabFunction(y, 'Vars',{x,c})
yfcn = function_handle with value:
@(x,c)[sqrt(2.0).*sqrt(c+cos(x));-sqrt(2.0).*sqrt(c+cos(x))]
xv = linspace(-5, 10, 25);
cv = 0:5;
[X,C] = ndgrid(xv,cv);
ymtx = yfcn(X,C);
% Q1s = size(ymtx)
figure
surf(X,C,real(ymtx((1:numel(xv)),:)))
hold on
% surf(X,C,imag(ymtx((1:numel(xv)),:)))
surf(X,C,real(ymtx((1:numel(xv))+numel(xv),:)))
% surf(X,C,imag(ymtx((1:numel(xv))+numel(xv),:)))
hold off
grid on
xlabel('x')
ylabel('c')
zlabel('y(x,c)')
figure
plot(xv, real(ymtx((1:numel(xv)),:)))
hold on
plot(xv,real(ymtx((1:numel(xv))+numel(xv),:)))
hold off
grid on
xlabel('x')
ylabel('y')
legend(compose('c = %d',cv), 'Location','bestoutside')
figure
fsurf(y, [-5 10 1 5])
xlabel('x')
ylabel('c')
zlabel('y(x,c)')
Make appropriate changes to get the result you want.
EDIT — 13 Aug 2021 at 15:42)
Corrected typographical error in the second figure plot calls (originally plotted against wrong variable).
.

More Answers (1)

Matt J
Matt J on 13 Aug 2021
for c=1:5
fimplicit( @(x,y) y.^2/2-cos(x) - c)
hold on
end
hold off
xlim([-5,10])

Community Treasure Hunt

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

Start Hunting!