trying to allow the user to choose the time length of a simulation
1 view (last 30 days)
Show older comments
Not sure where im going wrong, havent used matlabs for very long so it could be a rookie mistake.
Error in testing (line 45)
[t,x] = ode45(@(t,x) Matlab_SpringSystem_done(t,x,M,Ks,Kv,F), (time_duration_of_simulation), [0
0])
any help is appreciated, thanks
0 Comments
Answers (1)
BhaTTa
on 18 Mar 2025
Edited: BhaTTa
on 18 Mar 2025
Hey @nnnnnew01, I see that you're trying to run a simulation using MATLAB's ode45 function for solving ordinary differential equations (ODEs). The error you're encountering might be due to how the time span for the simulation is specified. The time span should be defined atleast two-element long vector.
Please refer to below code for refernce and modify it accordingly:
% Define constants
M = 1; % Mass
Ks = 100; % Spring constant
Kv = 10; % Damping constant
F = 1; % External force
% Ask the user to input the duration of the simulation
simulation_duration = input('Enter the duration of the simulation in seconds: ');
% Define the time span for the simulation
start_time = 0;
end_time = simulation_duration;
time_span = [start_time, end_time];
% Initial conditions
initial_conditions = [0; 0]; % Example: initial position and velocity
% Solve the ODE using ode45
[t, x] = ode45(@(t, x) Matlab_SpringSystem_done(t, x, M, Ks, Kv, F), time_span, initial_conditions);
% Plot the results
figure;
plot(t, x(:,1)); % Plotting position over time
xlabel('Time (s)');
ylabel('Position');
title('Spring System Simulation');
grid on;
% Define the ODE function
function dxdt = Matlab_SpringSystem_done(t, x, M, Ks, Kv, F)
% x(1) is position, x(2) is velocity
dxdt = zeros(2,1);
dxdt(1) = x(2);
dxdt(2) = (F - Kv*x(2) - Ks*x(1)) / M;
end
2 Comments
Walter Roberson
on 18 Mar 2025
The tspan parameter needs to be a vector with at least two elements. If you use exactly two elements, then ode45() will internally generate the list of times to return values at (typically irregularly sampled times.) If you use three or more elements in tspan, then ode45() will return data only for the listed times.
So time_span does not need to be two elements long, but it must be at least two elements long.
See Also
Categories
Find more on Ordinary Differential Equations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!