How to call a function in a for loop in MATLAB?
I would like to call (execute) an m-file (function) in a loop like this:
global m, r
m = 2;
for n = 2:10;
for r1 = 0:n-m;
r2 = n-m-r1;
r = [r1,r2];
[Call the function here?????????]
end
end
This is the function:
function main
x0 = [-0.5403,0.5471];
fsolve(@fcn,x0)
function z = fcn(X)
rand('twister',5409);
global m, r
a = rand(m,1);
for i = 1:m
sm(i) = 0.0;
for l = 开发者_开发技巧m-i+1:m
sm(i) = sm(i)+r(l);
end
s = 1.0/(i+sm(i));
g(i) = (a(i))^s;
end
prod = 1.0;
for k = 1:m
prod = prod * g(m+1-k);
u(k) = 1.0-prod;
x(k) = (sqrt(3)/pi)*log(u(k)/(1-u(k)));
end
sum = 0;
sum1 = 0;
sum2 = 0;
for j = 1:m
sum = sum+(r(j)+2)*(1/(1+exp((-pi/sqrt(3))*((x(j)-X(1))/X(2)))));
sum1 = sum1+(r(j)+2)*((x(j)-X(1))/X(2))*(1/(1+exp((-pi/sqrt(3))*((x(j)-X(1))/X(2)))));
sum2 = sum2+(x(j)-X(1))/X(2);
end
z(1) = pi/(X(2)*sqrt(3))*(-m+sum);
z(2) =(-1/X(2))*(m+(pi/sqrt(3))*(sum2-sum1));
Thank you very much for your help.
The functions main
and fcn
should be saved in a file called "main.m". You have to make sure this file is either in your current working directory or somewhere on the MATLAB path (as mentioned in a comment by Amro) so that MATLAB can get to it. Since main
requires no input arguments and has no output arguments, you could then just call it in any one of the following ways:
main
main;
main()
main();
If you have a function Main.m
Main.m
function out = main(in)
% blah blah blah
You would call the function
in = 2;
out = main(in)
Does this make sense?
Personnally I would create your function without a main() part.
create a file called fcn.m with your function fcn in it, make sure it's in your working directory or in your matlab path and then call it inside your loop.
addpath(genpath('/the/path/to/your/function/');
global m, r
m = 2;
for n = 2:10;
for r1 = 0:n-m;
r2 = n-m-r1;
r = [r1,r2];
z=fcn(r)
end
end
精彩评论