How to call a function in a for loop in MATLAB?

I would like to call (execute) 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));

      

Many thanks for your help.

+2


source to share


3 answers


Functions main

and fcn

should be saved in a file named main.m. You have to make sure that this file is either in your current working directory or somewhere in the MATLAB path (as Amro mentions in the comment ) for MATLAB to get to it. Since main

it takes no input arguments and has no output arguments, you can simply call it in one of the following ways:



main
main;
main()
main();

      

+6


source


If you have a Main.m function

main.m

function out = main(in)
% blah blah blah

      




You would call the function

in = 2;
out = main(in)

      

It makes sense?

+3


source


I would create your function without the main () part.

create a file called fcn.m with your fcn function in it, make sure it's in your working directory or in your matlab path, 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

      

+3


source







All Articles