Reputation: 91
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)
Upvotes: 1
Views: 210
Reputation: 608
You may be looking for arrayfun. This allows you to apply an array of numbers to the same function.
For example if I have the following function:
function y = power(x)
y = x*x;
end
Then I can use it as follows to apply it to different values:
X = [1 2 3];
arrayfun(@(x) power(x),X,'UniformOutput',false);
As you can see I'm using an anonymous function to wrap the power function. Also I'm using 'UniformOutput' to be false so the function can return different types of elements inside a cell array. If you don't want cell arrays set it to true.
Upvotes: 1
Reputation: 25992
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...
Upvotes: 1