Search code examples
matlabnested-loopsrunge-kutta

Solving Differential Equations IN MATLAB For Different Values Of Input


I have written a function plus a script to calculate and plot the response of a 1-degree-of-freedom system using 4th order runge-kutta method in matlab. Here is the thing that I want to plot the response of the system for different values of inputs. I have zero initial conditions and the input is as follows:

F(t) = 5*sin(w*t)

Where w = [2 5 10]

I don't know how to use a loop in my function to form the state space for all values of w and solve my equation and plot it for different values of w which makes a different input for each iteration. Notice that one way to do is write three different functions for all three cases and calculate the response.I do not want that. I just want a single function and my script which uses ode45 function to solve my differential equation but to plot the response for all values of w. How would You suggest me to do that. Here are my script and function:

function xDot = Myfnc(t,x)
global w
f = 5*sin(w*t);
%% Using State Space 

A = [0 1;-100 -1];
b = [0 f]';
xDot = A*x+b;
end




clc;
clear
close all;
%%
% y(..)+y(.)+100y = f(t)
% ZERO INITIAL conditions
% To A Harmonic Input
t = 0:0.1:15;
global w
w = 2;
Ics = [0 0];

[T,Y] = ode45(@Myfnc,t,Ics);

% plot(T,Y(:,1),'r','LineWidth',4)
% grid on
% hold on
% plot(T,Y(:,2),'k','LineWidth',3)

Solution

  • What prevents you to loop over the values for w?

    for w in [2 5 10]
      [T Y] = ode45(@(t,y)Myfnc(t,y,w),t,Ics,opts)
      plot...