I've been working in a project and every time I run this code in my computer it doesn't show the three graph it is suposed to graph. I have a function define and saved:
function [dydt] = spring_mass_system(t,y)
%Definition of 2nd order ODE for the spring-mass system
m = 20;
c(1)=5;
c(2)=40;
c(3)=200;
k = 20;
for i=1:3
dydt = zeros(2,1); %define colum array for output
dydt(1) = y(2);
dydt(2) = - (c(i)/m) * y(2) - (k/m) * y(1);
end
end
and I call my function by this script where I (supposedly) graph the three results in the the same picture. I run it in another computer and it does it how I want it. Any suggestion how to make this work properly, please? You can see I've added suggestion found online but, I it doesn't do anything to me.
tspan = [0,15];
ic = [0 1];
[t,y] = ode45(@spring_mass,tspan,ic);
figure;
plot(t,y(:,2));
grid;
xlabel('Time (s)');
ylabel('Dispalcement (m)');
hold on
thank you so much for your help.

 Akzeptierte Antwort

Star Strider
Star Strider am 6 Dez. 2019

0 Stimmen

The plot call you posted has it only plotting the second output of ‘spring_mass_system’.
It doesn’t show three lines because ‘spring_mass_system’ only returns two. That is how you wrote your ‘spring_mass_system’ ODE function.

4 Kommentare

Lazaro Gonzalez
Lazaro Gonzalez am 6 Dez. 2019
Bearbeitet: Lazaro Gonzalez am 6 Dez. 2019
But even with two values, should it show two line at least, isn't it?
It does if you change the plot call to:
plot(t,y);
Your existing code has it only plotting the second column of ‘y’.
Lazaro Gonzalez
Lazaro Gonzalez am 6 Dez. 2019
You were right. I am just plotting the second function values. I changed the value of my output vector but I am not getting any changes in my answer other than graphying y (with the last code you sent) and the previous answer.
Star Strider
Star Strider am 6 Dez. 2019
If you want to plot position, velocity, and acceleration as functions of time, you need to write your ‘spring_mass_system’ differential equations to provide them. That will give you the (Nx3) ‘y’ matrix you want.
Since this appears to be a homework assignment, I leave that to you.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Programming finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by