Are the variables passing through ode45?
Show older comments
Hi, I have two arrays - k1 and k2. I am trying to solve the ode45 in the for loop by varying the k1 and k2. Since k1 and k2 are global, I did not include it as an input for the function. My question is - why are my outputs of the ode45 the same for all of the k1 and k2 I pass in?
keff = 18000;
k2RangeHop = [linspace(25,55,6).*1000 35000000];
k1RangeHop = (k2RangeHop.*keff)./(k2RangeHop-keff);
initialStates(1) = L0+l0; % initial y
initialStates(2) = -1.2830; % initial yDot
y1_2a = zeros(25,7);
yDot_2a = zeros(25,7);
yDDot_2a = zeros(24,7);
groundReactionForce = zeros(24,7);
y2_2a = zeros(25,7);
deltaL = zeros(25,7);
for i = 1:length(k1RangeHop)
k1 = k1RangeHop(i);
k2 = k2RangeHop(i);
options = odeset('events', @endStance);
[t,states] = ode45(@(t,states) springMass(t,states),timespan, initialStates,options);
disp(k1)
disp(states)
y1_2a(:,i) = states(:,1);
yDot_2a(:,i) = states(:,2);
yDDot_2a(:,i) = diff(yDot_2a(:,i),1);
groundReactionForce(:,i) = yDDot_2a(:,i);
y2_2a(:,i) = ((-k1.*L0)+(k1.*y1_2a(:,i))+(k2.*l0))./(k2-k1);
deltaL(:,i) = -L0 + (y1_2a(:,i)-y2_2a(:,i));
end
function stateDot = springMass(t, states)
global k1 k2 m g L0 l0
% Equations of motion
y_pos = states(1);
yDot = states(2);
yDDot = -g + ((1/m)*((k1*k2)/(k1+k2))*((L0+l0)-y_pos)); % YOUR CODE HERE
% Collect all states
stateDot = [yDot;yDDot]; % YOUR CODE HERE
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%% End stance
function [value, isterminal, direction] = endStance(t, states) % end stance
% returns event function for passive walking simulation
global k1 k2 L0 l0
% The event occurs when value = 0. For this problem, the simulation should
% stop when the leg spring is extended beyond its resting length
y1 = states(1);
y2 = ((-k1*L0)+(k1*y1)+(k2*l0))/(k2+k1);
cll = y1 - y2; % current leg length
value = L0 - cll; % YOUR CODE HERE
isterminal = 1;
direction = -1;
end
4 Comments
Vanessa Chung
on 10 Nov 2023
Do you see the reason for identical results ?
keff = 18000;
k2RangeHop = [linspace(25,55,6).*1000 35000000];
k1RangeHop = (k2RangeHop.*keff)./(k2RangeHop-keff);
(k1RangeHop.*k2RangeHop)./(k1RangeHop+k2RangeHop)
Stephen23
on 11 Nov 2023
"Since k1 and k2 are global..."
Avoid using global variables.
"...I did not include it as an input for the function."
You should pass them as function inputs:
Answers (1)
Steven Lord
on 10 Nov 2023
0 votes
I recommend you not use global variables to share data between the ODE function and the function where you call ode45 with the ODE function as input. Instead use one of the techniques shown on this documentation page. Since you're already using anonymous functions, that technique would probably be easiest to adapt your code to use.
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!