## For loop not executed correctly

Asked by Chin-Fa Chung

### Chin-Fa Chung (view profile)

on 13 Oct 2018
Latest activity Edited by Walter Roberson

on 15 Oct 2018

### madhan ravi (view profile)

Hi, I write the code incorporates for loop with "fsolve" function. But it seems that it does not executed correctly. In my code, I started my loop with "for n=[1,2,3]" but it was run by the order of 0,0,3 instead of 1,2,3
Below is my code:
Cl=0.8;
Cd=0.2;
dair=1.2;
A=0.2;
Vc=40;
t=10;
global acc
global gama
global L
global D
acc=Vc/t;
for n=[1,2,3]
guess=[10,50];
V=0+acc*n;
gama=90-n*90/(Vc/acc);
L=Cl*0.5*dair*V^2*A;
D=Cd*0.5*dair*V^2*A;
q=fsolve(@thrustandangle,guess)
end
Here is the function called "thrustandangle" I used to solve two unknowns
function thrustandangle=thrustanglereq(x)
% x1=Tav
% x2=at
global L
global D
global acc
global gama
w=1.4;
g=9.81;
thrustandangle(1)=x(1)*sind(x(2))-w*g*cosd(gama)+L;
thrustandangle(2)=x(1)*cosd(x(2))-(w*acc)-D-w*sind(gama);
end
Can you kindly help me with this issue?
Thanks

Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 14 Oct 2018
Note that you should replace those global variables with a parameterized anonymous function:
This will give you simpler, less buggy, more efficient code:
function out = tafun(x,L,D,acc,gama)
% x1=Tav
% x2=at
w = 1.4;
g = 9.81;
out(1) = x(1)*sind(x(2))-w*g*cosd(gama)+L;
out(2) = x(1)*cosd(x(2))-(w*acc)-D-w*sind(gama);
end
And call it like this:
Cl = 0.8;
Cd = 0.2;
dair = 1.2;
A = 0.2;
Vc = 40;
t = 10;
acc = Vc/t;
guess = [10,50];
for n = 1:3
V = 0+acc*n;
gama = 90-n*90/(Vc/acc);
L = Cl*0.5*dair*V^2*A;
D = Cd*0.5*dair*V^2*A;
fun = @(x)tafun(x,L,D,acc,gama);
q = fsolve(fun,guess)
...
end
Chin-Fa Chung

### Chin-Fa Chung (view profile)

on 15 Oct 2018
Hi, Stephen. Thanks for a very valuable suggestion. I heard before you must be very careful when using global variable. I will learn "parameterized anonymous function" first And try it
Thanks

### madhan ravi (view profile)

on 13 Oct 2018
Edited by madhan ravi

### madhan ravi (view profile)

on 13 Oct 2018

for n=1:3
q=fsolve(@thrustandangle,guess)
put
q=fsolve(@thrustanglereq,guess)

Chin-Fa Chung

### Chin-Fa Chung (view profile)

on 13 Oct 2018
Thanks for helping Sir I will try