Plotting 2 functions on the same graph

2 views (last 30 days)
Eli Wolkenstein on 12 May 2022
Answered: Bjorn Gustavsson on 12 May 2022
I used this code to get a plot for Pos1 and Pos2. How can I modify it to make both curves appear on the same graph?
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 15;
fprintf('Beginning to run %s.m ...\n', mfilename);
legendStrings = cell(2, 1);
loopCounter = 1;
numElements = 1980; % HDTV resolution
p1 = subplot(2, 1, 1);
% Construct t
t = linspace(-10, 10 , numElements);
% Get x1
x1 = Pos1(t);
plot(t, x1, '-', 'LineWidth', 2);
grid on;
hold on;
title('Mass 1')
xlabel('t');
ylabel('x')
drawnow;
p2 = subplot(2, 1, 2);
% Construct t
t = linspace(-10, 10 , numElements);
% Get x2
x2 = Pos2(t);
plot(t, x2, '-', 'LineWidth', 2);
grid on;
hold on;
title('Mass 2')
xlabel('t');
ylabel('x')
drawnow;
legend(p1, legendStrings, 'Location', 'north');
legend(p2, legendStrings, 'Location', 'north');
function y = Pos1(t)
b11=-0.0553851;
b21=1;
c1=-0.0553686;
c2=0;
c3=-.996933;
c4=0;
w1=sqrt(-(-2.00554));
w2=sqrt(-(-0.194461));
y=c1*b11*cos(w1*t)+c2*b11*sin(w1*t)+c3*b21*cos(w2*t)+c4*b21*sin(w2*t);
end
function y = Pos2(t)
b12=18.0554;
b22=1;
c1=-0.0553686;
c2=0;
c3=-.996933;
c4=0;
w1=sqrt(-(-2.00554));
w2=sqrt(-(-0.194461));
y=c1.*b12.*cos(w1.*t)+c2.*b12.*sin(w1.*t)+c3.*b22.*cos(w2.*t)+c4.*b22.*sin(w2.*t);
end

Bjorn Gustavsson on 12 May 2022
Skip the calls to subplot? That would make your scrip "not put the graphs in 2 separate axes":
x1 = Pos1(t);
x2 = Pos2(t);
ph1 = plot(t, x1, '-', 'LineWidth', 2);
grid on;
hold on;
ph2 = plot(t, x2, '-', 'LineWidth', 2);
xlabel('t');
ylabel('x')
legend([ph1,ph2],'Mass1','Mass2')
drawnow;
Use a single call to plotyy? Use the double-axis capability available through yyaxis. Check the help and documentation to those functions.
HTH

R2022a

Community Treasure Hunt

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

Start Hunting!