Cannot pass function handle as an argument of a function - function

I'm new to Matlab and I'm trying to write custom function in matlab that would take function handle as one of its arguments.
I'm getting this error all the time:
Error using subsindex
Function 'subsindex' is not defined for values of class 'function_handle'.
Trying to debug I performed following test: I run command x = fminbnd(#humps, 0.3, 1). I proceeded as expected - I got result x = 0.6370.
So I created custom function called train and I copied ALL the code of function fminbnd to the file train.m. The only thing that I changed is the name, so that code of functions fminbnd and train is now identical except for the names.
Now I run both functions with the same argument and the custom function throws error while original fminbnd returns correct answer.
Here is the code:
>> x = fminbnd(#humps, 0.3, 1)
x =
0.6370
>> x = train(#humps, 0.3, 1)
Error using subsindex
Function 'subsindex' is not defined for values of class 'function_handle'.
Here is header of function train (everything else is copied from fminbnd):
function [xf,fval,exitflag,output] = train(funfcn,ax,bx,options,varargin)
Where is the problem?

Doing a which train showed me that there is a function in the neural network toolbox of the same name.
/Applications/MATLAB_R2009b.app/toolbox/nnet/nnet/#network/train.m % network method
You may be running the nnet train.m rather than the one you think you're running. Are you in the directory containing your train.m? When I made sure I was in the right directory, I got it to work:
>> which train
/Users/myuserid/train.m
>> x = train(#humps,0.3,1)
x =
0.6370
Maybe you can name your file something else like myfminbnd.m instead?

Instead of duplicating the whole fminbnd function, try:
function varargout = myfminbnd(varargin)
varargout = cell(1,nargout(#fminbnd));
[varargout{:}] = fminbnd(varargin{:});
end
this will work as an "alias" to the existing function:
>> fminbnd(#(x)x.^3-2*x-5, 0, 2)
ans =
0.8165
>> myfminbnd(#(x)x.^3-2*x-5, 0, 2)
ans =
0.8165
(you can get the other output arguments as well)

Related

Why Octave doesn't see this object?

I wanted to code a function in octave, however I found some problems during doing so:
N=700;
T=900;
lambda=N/T;
x=randn(N,T);
s=std(x(:));
r=x*x'/T;
l=eig(r);
lambda_plus=(s^2)*(1+sqrt(lambda))^2;
lambda_minus=(s^2)*(1-sqrt(lambda))^2;
# Define a function - value of this function depenends
# on position of x
function kiki = avg (x)
if (x <= lambda_plus && x >= lambda_minus)
(1/(2*pi*lambda*x*s^(2)))*sqrt((lambda_plus-x)*(x-lambda_minus));
else
0
endif
endfunction
Then I wanted to run this function so I did run avg(2) but it didn't work.
Error I saw was:
error: 'lambda_plus' undefined near line 15, column 15
but it's not true! lambda_plus is defined before the definition of the function!
I read that this problem might be, because octave doesn't see our function and the solution is to:
(1) Save the file with name of the function - in my case avg.m
(2) Open a new file and in new file run your function
I did exactly what they were saying and in newly created file I ran avg(2) but unfortunately with exactly same result.

Error : 'x' undefined

I got a problem with running Octave function (ODE), I've tried already present solutions for this problem but nothing is working. I've also tried by saving my filename as egzamin.m but it too not worked.
Code from octave :
function dx=egzamin(x,t)
dx=zeros(4,1);
b=0;
g=9.81;
x1=x(1);
y1=x(2);
Vx=x(3);
Vy=x(4);
dx(1)=Vx;
dx(2)=Vy;
dx(3)=-b*Vx*sqrt(Vx.^2+Vy.^2);
dx(4)=-b*Vy*sqrt(Vx.^2+Vy.^2)-g;
endfunction
N=mod(291813,100);
x1=0;
y1=0;
Vx=20+N;
Vy=20+N;
t=0:0.01:500;
sol=lsode("egzamin",[x1,y1,Vx,Vy],t);
plot(sol(:,1),sol(:,2))
The error is :
error: 'x' undefined near line 5 column 4
error: called from
egzamin at line 5 column 3
Since the file starts with function, it is not a script file,
as explained in the doc:
Unlike a function file, a script file must not begin with the keyword
function
Add any statement (even dummy like 1;) before the function line to get a script file.
# dummy statement to get a script file instead of a function file
1;
function dx=egzamin(x,t)
g = 9.81;
Vx = x(3);
Vy = x(4);
dx = [Vx, Vy, 0, -g];
endfunction
N=mod(291813,100);
x1=0;
y1=0;
Vx=20+N;
Vy=20+N;
t=0:0.01:500;
sol=lsode("egzamin",[x1,y1,Vx,Vy],t);
plot(sol(:,1),sol(:,2))
A very clear explanation of what's going on is given here.
You need to save the function (thus from function to endfunction and naught else) as egzamin.m, and then execute the rest of the code in a script or at the command line. Alternatively, provided Octave does that the same as what MATLAB does nowadays, first put your script (N=(..) to plot()) and then the function.
This is necessary since you are defining your function first, so it doesn't have any inputs yet, as you don't define them until later. The function needs to have its inputs defined before it executes, hence you need to save your function separately.
You can of course save your "script" bit, thus everything which is currently below your function declaration, as a function as well, simply don't give it in- and outputs, or, set all the input parameters here as well. (Which I wouldn't do as it's the same as your
egzamin then.) e.g.
function []=MyFunc()
N=mod(291813,100);
x1=0;
y1=0;
Vx=20+N;
Vy=20+N;
t=0:0.01:500;
sol=lsode("egzamin",[x1,y1,Vx,Vy],t);
plot(sol(:,1),sol(:,2))
endfunction

How do I set a function to a variable in MATLAB

As a homework assignment, I'm writing a code that uses the bisection method to calculate the root of a function with one variable within a range. I created a user function that does the calculations, but one of the inputs of the function is supposed to be "fun" which is supposed to be set equal to the function.
Here is my code, before I go on:
function [ Ts ] = BisectionRoot( fun,a,b,TolMax )
%This function finds the value of Ts by finding the root of a given function within a given range to a given
%tolerance, using the Bisection Method.
Fa = fun(a);
Fb = fun(b);
if Fa * Fb > 0
disp('Error: The function has no roots in between the given bounds')
else
xNS = (a + b)/2;
toli = abs((b-a)/2);
FxNS = fun(xns);
if FxNS == 0
Ts = xNS;
break
end
if toli , TolMax
Ts = xNS;
break
end
if fun(a) * FxNS < 0
b = xNS;
else
a = xNS;
end
end
Ts
end
The input arguments are defined by our teacher, so I can't mess with them. We're supposed to set those variables in the command window before running the function. That way, we can use the program later on for other things. (Even though I think fzero() can be used to do this)
My problem is that I'm not sure how to set fun to something, and then use that in a way that I can do fun(a) or fun(b). In our book they do something they call defining f(x) as an anonymous function. They do this for an example problem:
F = # (x) 8-4.5*(x-sin(x))
But when I try doing that, I get the error, Error: Unexpected MATLAB operator.
If you guys want to try running the program to test your solutions before posting (hopefully my program works!) you can use these variables from an example in the book:
fun = 8 - 4.5*(x - sin(x))
a = 2
b = 3
TolMax = .001
The answer the get in the book for using those is 2.430664.
I'm sure the answer to this is incredibly easy and straightforward, but for some reason, I can't find a way to do it! Thank you for your help.
To get you going, it looks like your example is missing some syntax. Instead of either of these (from your question):
fun = 8 - 4.5*(x - sin(x)) % Missing function handle declaration symbol "#"
F = # (x) 8-4.5*(x-sin9(x)) %Unless you have defined it, there is no function "sin9"
Use
fun = #(x) 8 - 4.5*(x - sin(x))
Then you would call your function like this:
fun = #(x) 8 - 4.5*(x - sin(x));
a = 2;
b = 3;
TolMax = .001;
root = BisectionRoot( fun,a,b,TolMax );
To debug (which you will need to do), use the debugger.
The command dbstop if error stops execution and opens the file at the point of the problem, letting you examine the variable values and function stack.
Clicking on the "-" marks in the editor creates a break point, forcing the function to pause execution at that point, again so that you can examine the contents. Note that you can step through the code line by line using the debug buttons at the top of the editor.
dbquit quits debug mode
dbclear all clears all break points

Passing variables into a function in Lua

I'm new to Lua, so (naturally) I got stuck at the first thing I tried to program. I'm working with an example script provided with the Corona Developer package. Here's a simplified version of the function (irrelevant material removed) I'm trying to call:
function new( imageSet, slideBackground, top, bottom )
function g:jumpToImage(num)
print(num)
local i = 0
print("jumpToImage")
print("#images", #images)
for i = 1, #images do
if i < num then
images[i].x = -screenW*.5;
elseif i > num then
images[i].x = screenW*1.5 + pad
else
images[i].x = screenW*.5 - pad
end
end
imgNum = num
initImage(imgNum)
end
end
If I try to call that function like this:
local test = slideView.new( myImages )
test.jumpToImage(2)
I get this error:
attempt to compare number with nil
at line 225. It would seem that "num" is not getting passed into the function. Why is this?
Where are you declaring g? You're adding a method to g, which doesn't exist (as a local). Then you're never returning g either. But most likely those were just copying errors or something. The real error is probably the notation that you're using to call test:jumpToImage.
You declare g:jumpToImage(num). That colon there means that the first argument should be treated as self. So really, your function is g.jumpToImage(self, num)
Later, you call it as test.jumpToImage(2). That makes the actual arguments of self be 2 and num be nil. What you want to do is test:jumpToImage(2). The colon there makes the expression expand to test.jumpToImage(test, 2)
Take a look at this page for an explanation of Lua's : syntax.

How to pass a function as argument

I'm using Scilab and I'm trying to make a function like the following:
function p = binary_search(myf,a,b)
The target is to make a binary_search to find such p that: myf(p) = 0 in [a,b].
I want to do something like this:
root = binary_search("x^3 - 10",1,2)
Where the first string is a definition of a function.
The only way I found is defining a function called x3:
function x = x3(p)
x = p^3 - 10;
endfunction
and then, inside binary_search, do something like:
fa = x3(a);
Any ideas?
Thank You!
If you have defined the function f(x) = x^3 - 10 , either using deff('y=f(x)','y=x^3-10') or the regular "function ... endfunction" syntax, then you can simply pass f as an argument: define
function r = binary_search(f,a,b)
% do the binary search here and store the result in r
endfunction
Then you can call
---> binary_search(f, 1, 2)
which works fine in SciLab.
In MATLAB/octave, the interpreter considers " f " as an equivalent for f(), i.e., it would execute the function f without arguments, which will result in an error "x undefined". To avoid this, you have to type an # in front of f:
---> binary_search( #f, 1, 2) %% in MATLAB/octave
Functions in Scilab can be passed as arguments to other functions. Therefore, if you have one function, f:
function y=f(x)
y = x^3 - 10
endfunction
you are free to pass that to another function,
root = binary_search("x^3 - 10",1,2)
deff is simply a way to quickly define a function- usually inline on the interpreter.
Alternatively, you can also pass an expression as a string to a function and have that evaluated using the evstr command:
function p = binary_search(expression, a, b)
evstr expression
//Rest of your code
endfunction
You would implement this on the interpreter thus:
expression = "a^3 - 10"
root = binary_search(expression, 1, 2)
I found a solution:
In the main window (the interpreter), I define the function like:
deff('[y] = square(x)','y=x^2')
Then, I call
bi(square,0,2)
In the function, I just do 'f(x)':
function [x] = bi(f,a,b)
fa = f(a);