why do i get fminsearch undefined function error [closed] - matlab

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to optimize a function with 2 inputs. Trying to use fminsearch but it keeps saying undefined function or variable although it is already defined.
I have already defined the function in a separate script that is in the same directory with my main script. I have a classroom license which includes optimization toolbox and there is no spelling mistake while calling the function.
function o=u(x,y)
%some code here
end
%in a second script
init=[0.1,0.1];
b=fminsearch(o,init);
The error is:
Undefined function or variable 'o'.

From the documentation on fminsearch, the function being minimized must have a single argument and accessed with a function handle (see this related answer).
The error you are getting is because you can't call o and use it as an input to fminsearch() since o is undefined. To get o, you have to first get u(x,y), plus as mentioned, fminsearch requires a function handle as an input.
You have several options that still use your standalone function, u(x,y).
1. Create a function handle
Define a function handle that calls u(x,y) but has a single argument which is a 2 x 1 vector, z = [x; y].
fh =#(z) u(z(1),z(2));
z0 = [1; 2]; % Initial Guess for z = [x; y]
[z,TC] = fminsearch(fh,z0)
2. Change the function and call it directly
The same result is possible with
[z,TC] = fminsearch(#u,z0)
if you redefine u(x,y) to be as follows:
function o=u(z)
x = z(1);
y = z(2);
% your function code here
end

Related

Changing function variable to another variable MATLAB [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
Is there a way to change a function variable to another variable?
for instance, if I have the function:
f = #(s) exp(2-s)
I need to change it to
f = #(t) exp(2-t)
without changing it manually.
With the usual caveats that this is a terrible idea :) let's get a little nuts.
First, we can make the anonymous function f
f = #(s) exp(2-s)
For some sample uses, for sanity
f(1) % 2.71828182845905
f(10) % 0.000335462627902512
Now, save it to a file, using the -v7.3 flag to force an H5 file type
save('tempfile','f','-v7.3')
Matlab can read this file as data. After some exploring, we can see that the function is stored, as an evaluation-ready string, here:
char(h5read('tempfile.mat','/f/function_handle/function'))
% Returns 'sf%0#(s)exp(2-s)'
So, it's easy enough to change, using Matlab's H5 write functions
h5write('tempfile.mat','/f/function_handle/function',uint16('sf%0#(x)exp(2-x)'))
Let's see, did it work?
clear f
load('tempfile.mat')
Now we have the following
f =
function_handle with value:
#(x)exp(2-x)
f(1) % 2.71828182845905
f(10) % 0.000335462627902512
Now, we can see a lot of this data without the file saving business, using the functions function. (So meta)
>> f = #(s) exp(2-s);
>> functions(f)
ans =
struct with fields:
function: '#(s)exp(2-s)'
type: 'anonymous'
file: ''
workspace: {[1×1 struct]}
within_file_path: '__base_function'
This lets you see how Matlab is storing the anonymous function. When debugging, this allows you to see what baggage (stored workspaces and stuff) is associated with the function handle.
However, changes to this structure do not change the actual function handle. I don't know of a way to generate a new function handle from this structure.
Wrap up
[note #1 deleted]
Please, don't ever do this.

matlab function variable definition [duplicate]

This question already has answers here:
MATLAB not enough input arguments
(2 answers)
Closed 5 years ago.
In Matlab, I want to get the variables from the workspace for the function . But I did not do it.
For example; the function is:
function Y = objfun(x)
Y = 20+x(1).^2 + 2*x(2).^2 -15*x(3);
end
gives me the following problem when I run the function
>> objfun
Not enough input arguments.
Error in objfun (line 5)
Y = 20+x(1).^2 + 2*x(2).^2 -15*x(3);
x variable is exist in workspace like x= [4 5 7] and I don't want to write it inside of function. so what shall I do.
Maybe it is very east question for you but I don't know and I trid make it.
could you help me?
In Matlab (or Octave) you can use scripts or functions.
If you create script called objfun, you have what you are looking for. Just call it using objfun and it will use workspace variable x. The script is saved as objfun.m.
Functions are different. They can have arguments, but these arguments are local variables (only available within the function).
If you define a function, you must call it with the arguments.

using ode45 to solve y'=y adnd y'=t in Matlab

I first defined functions for dy/dt=y and dy/dt=t:
function dy=d(y):
dy=y
end
function ddy=dd(t):
ddy=t
end
And then I used ode45, respectively:
[t,y]=ode45('d',[1 10],1)
[t,y]=ode45('dd',[1 10],1)
which returns the following error: Error using d
Too many input arguments.
My question is:
Where did I go wrong?
How does Matlab know whether y or t is the independent variable? When I define the first function, it could be reasonably interpreted as dt/dy=y instead of dy/dt=y. Is there a built-in convention for defining functions?
First things first: the docs on ode45 are on the mathworks website, or you can get them from the console by entering help ode45.
The function you pass in needs to take two variables, y then t. As you noticed, with just one it would be impossible to distinguish a function of only y from a function of only t. The first argument has to be the independent, the second is the dependent.
Try defining your function as dy = d(t, y) and ddy = dd(t, y) with the same bodies.
one other note, while using a string representing the function name should work, you can use #d and #dd to reference the functions directly.

MATLAB Using fzero - returns error

I'm trying to use the MATLAB function fzero properly but my program keeps returning an error message. This is my code (made up of two m-files):
friction_zero.m
function fric_zero = friction_zero(reynolds)
fric_zero = 0.25*power(log10(5.74/(power(reynolds,0.9))),-2);
flow.m
function f = flow(fric)
f = 1/(sqrt(fric))-1.873*log10(reynolds*sqrt(fric))-233/((reynolds*sqrt(fric))^0.9)-0.2361;
f_initial = friction_zero(power(10,4));
z = fzero(#flow,f_initial)
The goal is to return z as the root for the equation specified by f when flow.m is run.
I believe I have the correct syntax as I have spent a couple of hours online looking at examples. What happens is that it returns the following error message:
"Undefined function or variable 'fric'."
(Of course it's undefined, it's the variable I'm trying to solve!)
Can someone point out to me what I've done wrong? Thanks
EDIT
Thanks to all who helped! You have assisted me to eventually figure out my problem.
I had to add another file. Here is a full summary of the completed code with output.
friction_zero.m
function fric_zero = friction_zero(re)
fric_zero = 0.25*power(log10(5.74/(power(re,0.9))),-2); %starting value for fric
flow.m
function z = flow(fric)
re = power(10,4);
z = 1/(sqrt(fric))-1.873*log10(re*sqrt(fric))-233/((re*sqrt(fric))^0.9)-0.2361;
flow2.m
f_initial = friction_zero(re); %arbitrary starting value (Reynolds)
x = #flow;
fric_root = fzero(x,f_initial)
This returns an output of:
fric_root = 0.0235
Which seems to be the correct answer (phew!)
I realised that (1) I didn't define reynolds (which is now just re) in the right place, and (2) I was trying to do too much and thus skipped out on the line x = #flow;, for some reason when I added the extra line in, MATLAB stopped complaining. Not sure why it wouldn't have just taken #flow straight into fzero().
Once again, thanks :)
You need to make sure that f is a function in your code. This is simply an expression with reynolds being a constant when it isn't defined. As such, wrap this as an anonymous function with fric as the input variable. Also, you need to make sure the output variable from your function is z, not f. Since you're solving for fric, you don't need to specify this as the input variable into flow. Also, you need to specify f as the input into fzero, not flow. flow is the name of your main function. In addition, reynolds in flow is not defined, so I'm going to assume that it's the same as what you specified to friction_zero. With these edits, try doing this:
function z = flow()
reynolds = power(10,4);
f = #(fric) 1/(sqrt(fric))-1.873*log10(reynolds*sqrt(fric))-233/((reynolds*sqrt(fric))^0.9)-0.2361;
f_initial = friction_zero(reynolds);
z = fzero(#f, f_initial); %// You're solving for `f`, not flow. flow is your function name
The reason that you have a problem is because flow is called without argument I think. You should read a little more about matlab functions. By the way, reynolds is not defined either.
I am afraid I cannot help you completely since I have not been doing fluid mechanics. However, I can tell you about functions.
A matlab function definition looks something like this:
function x0 = f(xGuess)
a = 2;
fcn =#(t) a*t.^3+t; % t must not be an input to f.
disp(fcn);
a = 3;
disp(fcn);
x0 = fsolve(fcn1,xGuess); % x0 is calculated here
The function can then ne called as myX0 = f(myGuess). When you define a matlab function with arguments and return values, you must tell matlab what to do with them. Matlab cannot guess that. In this function you tell matlab to use xGuess as an initial guess to fsolve, when solving the anonymous function fcn. Notice also that matlab does not assume that an undefined variable is an independent variable. You need to tell matlab that now I want to create an anonymous function fcn which have an independent variable t.
Observation 1: I use .^. This is since the function will take an argument an evaluate it and this argument can also be a vector. In this particulat case I want pointwise evaluation. This is not really necessary when using fsolve but it is good practice if f is not a matrix equation, since "vectorization" is often used in matlab.
Observation 2: notice that even if a changes its value the function does not change. This is since matlab passes the value of a variable when defining a function and not the variable itself. A c programmer would say that a variable is passed by its value and not by a pointer. This means that fcn is really defined as fcn = #(x) 2*t.^3+t;. Using the variable a is just a conveniance (constants can may also be complicated to find, but when found they are just a value).
Armed with this knowledge, you should be able to tackle the problem in front of you. Also, the recursive call to flow in your function will eventuallt cause a crash. When you write a function that calls itself like this you must have a stopping criterium, something to tell the program when to stop. As it is now, flow will call ifself in the last row, like z = fzero(#flow,f_initial) for 500 times and then crash. Alos it is possible as well to define functions with zero inputs:
function plancksConstant = h()
plancksConstant = 6.62606957e−34;
Where the call h or h() will return Plancks constant.
Good luck!

Load Multiple Functions from a Single File in Matlab [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is it possible to define more than one function per file in MATLAB?
Is it possible to load multiple functions from the same .m file in Matlab? I find it cumbersome to create a single file for each function for many small alias utility functions. I have already tried this tip which is allowed Octave, but not in my Matlab. I get the following error:
??? Error: File: /home/per/Documents/MATLAB/aliases.m Line: 6 Column: 1
Function definitions are not permitted in this context.
My aliases.m file currently contains
% Prevent Octave from thinking that this
% is a function file:
1;
function y = isvariable(x)
%Return non-zero if x is a function.
y = exist(x, 'var');
end
function y = isfile(x)
%Return non-zero if x is a function.
y = exist(x, 'file');
end
function y = isdir(x)
%Return non-zero if x is a function.
y = exist(x, 'dir');
end
function y = isbuiltin(x)
%Return non-zero if x is a function.
y = exist(x) == 5;
end
I'm afraid that is not possible, each m-file contains exactly one MATLAB function (you can have nested or sub-functions, but they are not accessible outside of the file).
If you are concerned about putting too much stuff on the global scope, think about OOP and namespaces.