MATLAB Answers


How to run function within for loop

Asked by Mirlan Karimov on 21 Mar 2019
Latest activity Commented on by Mirlan Karimov on 22 Mar 2019
Accepted Answer by Jan
The code given below solves the delayed type differential equation. I want to run this code for >10,000 different combinations of and . That is, and ;
function [sol]=system_simulation
po=1.4; do=8; tau=0.5; xth=0.2; vth=0.2;ksi=0.25;
option=odeset('RelTol', 1e-4, 'AbsTol', 1e-4);
sol = dde23(@syst,[tau],@hystory,[0 100],option);
figure(1), plot(sol.x,sol.y(1,:));
% --------------------------------------------------------------------------
function s = hystory(t)
% Constant history function for inverted pendulum.
s = [0.4;0.1];
% --------------------------------------------------------------------------
function xprime = syst(t,x,Z)


Mirlan - you want to iterate over po and do but nowhere do you reference them. How should they be used? (It is also doubtful you want to plot the results for all 10000 iterations so please discuss what you want to save/store from each iteration.
No plotting, I just want to store the data of sol.y(1,:) at each time iteration. Oh sorry it is p and d. There are some additional steps that turn po and do to p and d respectively depending on conditions but it has nothing to do now so I removed them.

Sign in to comment.


1 Answer

Answer by Jan
on 22 Mar 2019
Edited by Jan
on 22 Mar 2019
 Accepted Answer

I prefer providing parameters by anonymous functions instead of nested function. See Answers: Anonymous function for params . Then:
pv = 0.5:0.1:14;
dv = 0.5:0.1:14;
Result = cell(numel(pv), numel(dv));
ip = 0;
for p = pv
ip = ip + 1;
id = 0;
for d = dv
sol = dde23(@(t,x,Z) syst(t,x,Z, p, d), tau, ...
@hystory, [0, 100], option);
id = id + 1;
Result{ip, id} = sol.y(1,:);

  1 Comment

Sign in to comment.