# Using loop instead of hardcoding

1 view (last 30 days)
Khang Nguyen on 20 May 2019
Answered: Saumya Goel on 23 May 2019
Hi everyone,
%inputs
dvdt = @(t,v) t-v;
v0 = 1;
tspan = [0 1];
% h = 0.7
h = 0.7;
[ta,va] = midpoint(dvdt,tspan,v0,h);
%% h = 0.5
h = 0.5;
[tb,vb] = midpoint(dvdt,tspan,v0,h);
%% h = 0.1
h = 0.1;
[tc,vc] = midpoint(dvdt,tspan,v0,h);
%% h = 0.05
h = 0.05;
[td,vd] = midpoint(dvdt,tspan,v0,h)
%% MIDPOINT FUNCTION
if ~(tspan(2)>tspan(1))
error('upper limit must be greater than lower')
end
% Create all independent values, t
%use tspan to create a vector with spacing = h;
t = [tspan(1):h:tspan(2)]';
n = length(t);
if t(end) < tspan(2)
t(n+1) = tspan(2);
n = n+1;
end
% add extra t-value if needed
%check if final t-value can be achieved using the current h
%if not, add a new t-value to the end of t
% Implement Euler's method
%use a for loop
%pre allocate the solution vector
%y = zeros(1,n)
%y(1) = y0
y = y0*ones(n,1); % 1 line
for i = 1:n-1 %stop at n-1 because dont need to calculate the deriative for final interation
%singeline for euler's method
thalf = t(i) + (t(i+1)-t(i))/2;
yhalf = y(i) + (t(i+1)-t(i))/2 * dydt(t(i),y(i));%euler's with half step
y(i+1) = y(i) + (t(i+1)-t(i))*dydt(thalf,yhalf); %using derivative at half step
end
QUESTION:
Instead of just typing particular h and solving each h respectively, how can I make a loop for it ?.

Saumya Goel on 23 May 2019
You can create an array for h and then iterate usign for loop according to size of the array "h".
While storing the output of the for loop you can have two arrays as "t" and "v" which can be iterated over to store the results, instead of having different variables as ta,tb,tc and so on.
For example:
N = [1 2 3];
t = zeros(1,length(N));
v = zeros(1,length(N));
for n = 1 : length(N)
[t(n),v(n)] = val(N,n);
end
function [xyz,abc] = val(N,n)
xyz = N(n);
abc = N(n);
end