2

In order to get to know MATLAB a little bit better, I tried to run the following code which I found on a help file of MATLAB:

function F = myfun(x,c)
   F = [ 2*x(1) - exp(c*x(1))
        -x(1) - exp(c*x(2))
        x(1) - x(2) ];

   c = -1; % define parameter first
   x = lsqnonlin(@(x) myfun(x,c),[1;1])

However, I get the following error :

Error using F (line 2)
Not enough input arguments.

How is this possible? The two arguments necessary ( x and c) are stated in the definition of F, right?

Hope you can help me with this ! Many thanks in advance for your replies!

Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70
Justinnl
  • 27
  • 5

2 Answers2

0

Are you sure you are calling it the right way?

When I save this in myfun.m:

function F = myfun(x,c)
   F = [ 2*x(1) - exp(c*x(1))
        -x(1) - exp(c*x(2))
        x(1) - x(2) ];
end

And write this in the command window, it works:

c = -1; % define parameter first
x = lsqnonlin(@(x) myfun(x,c),[1;1])

x =  
    0.2983
    0.6960
Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70
  • Thank you very much. I tried to run the whole script at once. When I, like you showed me, first save the myfun.m part and then write the c and x statements in the command window, it works fluently. Is it possible to include both the function and the c and x statement in just one script? (sorry for this MatLab beginner level question ) – Justinnl Nov 10 '13 at 11:35
  • @Justinnl: You could even do it in a single statement if you _really_ want, `x = lsqnonlin(@(x) [ 2*x(1) - exp(c*x(1)); -x(1) - exp(c*x(2)); x(1) - x(2) ],[1;1])`, but I would stick with having `myfun` in a separate file. Check out [this question](http://stackoverflow.com/questions/5363397/in-matlab-can-i-have-a-script-and-a-function-definition-in-the-same-file), for some extra information regarding functions inside scripts. – Stewie Griffin Nov 10 '13 at 11:46
  • @ Robert P : thank you very much for the information. I am trying to get to know the matlab principles and you really helped me out with the functions topic. I will have a look at the question for the extra information. Thanks ! – Justinnl Nov 10 '13 at 15:29
-3

Put triple dot at the end of each incomplete line. And you don't need that square bracket.


    F = 2*x(1) - exp(c*x(1)) ...
        -x(1) - exp(c*x(2)) ...
        x(1) - x(2);

heriantolim
  • 457
  • 2
  • 9