## How to create a vector by iteration

### Faouzi Gheffar (view profile)

on 21 Jun 2019
Latest activity Edited by Jan

on 21 Jun 2019

### Jan (view profile)

Hello everyone,
I am new on Matlab and I have some questions about a program I am making.
I am working on a program that creates a vector from tthree other vector by iterations with the following formula : I would like to create the vector F whcih represent a baseline calculated by iteration from P1, P2 and G which also are vectors with the same number of elements.
Here are the steps I have to follow :
1. Define the vectors, G(t), Pl(t) and P2(t), so that all have an equal number of elements.
2. Set F(t) equal to Pl(t) and evaluate the right-hand side of Eq. 3.
3. Set the evaluated F(t) equal to the input F(t) and perform step 2 again. Repeat this procedure until F(t) does not change further when the output of the preceding iteration is put equal to the input of the next.
I am struggling at step 3. I don't know how to create the loop.
Here is my code for the moment :
% Iterative baseline using Bandara method
clear all
close all
% Variables
x = dataset(:,1);
y = dataset (:,2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Time vector
t = 27 : 1 : 218;
% Vectors P1 and P2
P1 = 0.000148 + -0.000182 * t.^1;
P2 = 0.027040 + -0.000329 * t.^1;
% Vector G
G = interp1(x,y,t);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Definition of F %%%%%
F0 = P1;
Fnew = zeros(1,length(t));
it = 1; % Iteration number
fun = @(t)G-F0;
while true
for ii = 1 : length(t)
Fnew(ii) = (integral(fun,t(1),t(ii),'ArrayValued',true) / integral(fun,t(1),t(end),'ArrayValued',true)) * (P2(ii) - P1(ii)) + P1(ii);
if Fnew(ii) - F0(ii) < 0.1
break
end
end
F0 = Fnew;
it = it+1;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
hold on
% plot(x,y,'r-','linewidth',2);
plot(t,P1,'linewidth',2);
plot(t,P2,'linewidth',2);
plot(t,G,'linewidth',2);
plot(t,Fnew,'linewidth',2);
Does anyone have an idea of what is wrong with my code ?
You will find enclosed the excel file related to the code.

on 21 Jun 2019
Edited by Jan

### Jan (view profile)

on 21 Jun 2019

The break stops the for loop, but there is no exit from the outer while loop:
while true
for ii = 1 : length(t)
Fnew(ii) = (integral(fun,t(1),t(ii),'ArrayValued',true) / integral(fun,t(1),t(end),'ArrayValued',true)) * (P2(ii) - P1(ii)) + P1(ii);
if Fnew(ii) - F0(ii) < 0.1
break
end
end
F0 = Fnew;
it = it+1;
end
Maybe you mean:
proceed = true;
while proceed
for ii = 1 : length(t)
Fnew(ii) = (integral(fun,t(1),t(ii),'ArrayValued',true) / ...
integral(fun,t(1),t(end),'ArrayValued',true)) * ...
(P2(ii) - P1(ii)) + P1(ii);
if Fnew(ii) - F0(ii) < 0.1
proceed = false; % Will stop the WHILE loop
break % exits the FOR loop
end
end
F0 = Fnew;
it = it+1;
end