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 8 years ago.
Improve this question
I have wrote a program which it has two functions. The first one's output is a matrix like:
Z = [1 2 3]
The second function should use the output of the previous one. But it can't read the matrix Z.
Can you help please?
My first function is something like this:
function ff = firststep(z)
sigme1=z(5)* exp(-z(1)*10^12*(t-z(2)*10^-6).^2).*cos(2*pi*z(3)*10^6*(t-z(2)*10^-6)+z(4));
ff =sum((y-sigme).^2)/NN;
end
it is used in an optimization toolbox which after optimizing it the output is a matrix z which I have in my workspace.
My second function is like this:
function ff = secstep(zz)
sigme1=zz(1)* exp(-z(1)*10^12*(t-zz(2)*10^-6).^2).*cos(2*pi*z(3)*10^6*(t-zz(2)*10^-6)+z(4));
end
I have also been attempting to optimize this function, but this time matlab can't call (what I meant by reading in my first post) matrix z.
The error is this:
Undefined function 'z' for input arguments of type 'double'.
After checking your code I should say that, you need to pass the variables to your function or make the variables global. check out the following link:
How declare a global variable in MATLAB
example:
function tic
% TIC Start a stopwatch timer.
% TIC; any stuff; TOC
% prints the time required.
% See also: TOC, CLOCK.
global TICTOC
TICTOC = clock;
function t = toc
% TOC Read the stopwatch timer.
% TOC prints the elapsed time since TIC was used.
% t = TOC; saves elapsed time in t, does not print.
% See also: TIC, ETIME.
global TICTOC
if nargout < 1
elapsed_time = etime(clock, TICTOC)
else
t = etime(clock, TICTOC);
end
I suggest you declare the z as a global variable in each function and in the main file simply:
global z
The optimization algorithm that I was using was GA(Genetic Algorithm). I wrote this function in order to get what I wanted:
function [zz,fvalzz] = secstep(z,NVARS)
[zz,fvalzz]=ga(#secfun,NVARS);
function ff = secfun(zz)
y=.5*exp(-35*10^12*(t-2e-6).^2).*cos(2*pi*5e6*(t-2e-6)+0);
sigme2=zz(1)* exp(-z(1)*10^12*(t-zz(2)*10^-6).^2).*cos(2*pi*z(3)*10^6*(t-zz(2)*10^-6)+z(4)); %z vector has been calculated from another function.
NN=length(y);
ff =sum((y-sigme2).^2)/NN;
end
end
Related
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
I have very limited knowledge on Matlab and I'm trying to make a general Newton Raphson function but every time it comes up with an error saying there are not enough input arguments. My code needs three inputs, f (the function), c0 (the initial guess) and n (the number of steps). This is my code so far:
function [c] = Q3(f,c0,n)
for i=1:n
c(0)=c0;
f=f(x);
fp=diff(f,x);
c(i)=c(i-1)-subs(f,x,c(i-1))/subs(fp,c(i-1));
end
disp(c)
I have this function written in a script file
g=#(x)(sin((pi.*x)/2)+(1/x)-(10.*x));
I then put this into the command window [c]=Q3(g(x),1,n) hoping it would work but obviously my code needs work.
Thanks
This should do the trick, the function g is defined as you stated:
g=#(x)(sin((pi.*x)/2)+(1/x)-(10.*x));
but also you should define n and c0, for example:
clearvars
g=#(x)(sin((pi.*x)/2)+(1/x)-(10.*x));
n=10
c0=1
c=Q3(g,c0,n)
And in another file you write the function for NR:
function [c] = Q3(f,c0,n)
h=1e-4;
c(1)=c0;
for i=1:n
g=f(c(i));
gp=(f(c(i)+h)-f(c(i)-h))/(2*h)
c(i+1)=c(i)-g/gp
end
disp(c)
In this case I choose h=1e-4 for the numerical derivative approximation, but you can change it. I suggest h<1e-2.
I have a class with properties in it (let say the name of the class file is inputvar),
I use it as the input argument for two different functions, which have an exactly the same calculation, but a little bit different code, which I'll explain later.
For the first function (let say the name is myfun1), I wrote the input argument like this:
f = myfun1 (inputvar)
So every time I want to use variables from the class inside the function, I'll have to call inputvar.var1, inputvar.var2, and etc.
For the second function (myfun2), I wrote each variables from the class in the input argument, so it looks like this:
f = myfun2 (inputvar.var1, inputvar.var2, ... etc )
Inside the function, I just have to use var1, var2, and etc, without having to include the name of the class.
After running both functions, I found that myfun2 runs a lot faster than myfun1, about 60% (I used tic-toc).
Can someone explain to me exactly why is that ?
with the reference:
MATLAB uses a system commonly called "copy-on-write" to avoid making a
copy of the input argument inside the function workspace until or
unless you modify the input argument. If you do not modify the input
argument, MATLAB will avoid making a copy. For instance, in this code:
function y = functionOfLargeMatrix(x) y = x(1); MATLAB will not make a
copy of the input in the workspace of functionOfLargeMatrix, as x is
not being changed in that function. If on the other hand, you called
this function:
function y = functionOfLargeMatrix2(x) x(2) = 2; y = x(1);
then x is being modified inside the workspace of functionOfLargeMatrix2, and so a copy must be made.
According to the statement above, when you directly pass a class object and you change any member of this object, a whole copy operation for the class is applied.
On the other side, with giving the class members as separate arguments, copy operation is applied only for the related members modified in the function, resulting in a faster execution.
I found that accessing properties is very slow in Matlab. I have not found a way around it, but some basic ideas are found here: http://blogs.mathworks.com/loren/2012/03/26/considering-performance-in-object-oriented-matlab-code/
But this article talks only about avoiding horrible, abysmal performance. Even with the simplest properties, performance is mediocre at best.
Take the example class from the Mathworks article. I did small test script:
clear all
clc
n = 1e5;
%% OOP way - abysimal
result = zeros(1, n);
tic
for i = 1:n
cyl = SimpleCylinder();
cyl.R = i;
cyl.Height = 10;
result(i) = cyl.volume();
end
toc
%% OOP Vectorized - fair
clear result
tic
cyl = SimpleCylinder();
cyl.R = 1:n;
cyl.Height = 10;
result = cyl.volume();
toc
%% for loop without objects - good
result = zeros(1, n);
tic
for i = 1:n
result(i) = pi .* i.^2 .* 10;
end
toc
%% Vectorized without objects - excellent
clear result
tic
R = 1:n;
result = pi .* R.^2 .* 10;
toc
With these results:
Elapsed time is 6.141445 seconds.
Elapsed time is 0.006245 seconds.
Elapsed time is 0.002116 seconds.
Elapsed time is 0.000478 seconds.
As you can see, every property access is slowing down. Try to vectorize (as always) but even the simple for-loop outperforms the vectorized OOP solution for small n. (On my PC, they break even at 1e7)
Essential message: OOP in Matlab is slow! You pay the price for every property access.
To your question: When you call
myfun2 (inputvar.var1, inputvar.var2, ... etc )
the values are copied. Within the function, you are no longer dealing with classes. Access to variables is fast. However, if you pass the whole class, every access to a property is slow. You can circumvent this by caching all properties in local variables and use these.
If you modify the class to inherit from handle everything gets a bit faster, but the difference is negligible.
I have this function:
function example(y)
global TICTOC;
tic
TICTOC=5;
toc
end
and I expect TICTOC=5 change the result of toc, since TICTOC is a global variable in tic and toc functions; but this is not the case; Does anyone know the reason?
I like to know the answer, because I 'm worried to declare a global variable, which it's name has been declared global in some other functions, I'm not aware of.
I saw this function in matlab 2008b help
function tic
% TIC Start a stopwatch timer.
% TIC; any stuff; TOC
% prints the time required.
% See also: TOC, CLOCK.
global TICTOC
TICTOC = clock;
function t = toc
% TOC Read the stopwatch timer.
% TOC prints the elapsed time since TIC was used.
% t = TOC; saves elapsed time in t, does not print.
% See also: TIC, ETIME.
global TICTOC
if nargout < 1
elapsed_time = etime(clock, TICTOC)
else
t = etime(clock, TICTOC);
end
thanks.
I think you can use assignin command to send the TICTOC value to base and thus changing the global value.
I use the assignin command to send parameters from function to Base.
Regards
Dilip
I don't know why but I the answer of my question is No. I checked it and it seems that it is not being overwritten. The reason must be because tic, toc is a built in Matlab function
Can somebody explain to me the meaning of the # (function handle) operator and why to use it?
The function handle operator in MATLAB acts essentially like a pointer to a specific instance of a function. Some of the other answers have discussed a few of its uses, but I'll add another use here that I often have for it: maintaining access to functions that are no longer "in scope".
For example, the following function initializes a value count, and then returns a function handle to a nested function increment:
function fHandle = start_counting(count)
disp(count);
fHandle = #increment;
function increment
count = count+1;
disp(count);
end
end
Since the function increment is a nested function, it can only be used within the function start_counting (i.e. the workspace of start_counting is its "scope"). However, by returning a handle to the function increment, I can still use it outside of start_counting, and it still retains access to the variables in the workspace of start_counting! That allows me to do this:
>> fh = start_counting(3); % Initialize count to 3 and return handle
3
>> fh(); % Invoke increment function using its handle
4
>> fh();
5
Notice how we can keep incrementing count even though we are outside of the function start_counting. But you can do something even more interesting by calling start_counting again with a different number and storing the function handle in another variable:
>> fh2 = start_counting(-4);
-4
>> fh2();
-3
>> fh2();
-2
>> fh(); % Invoke the first handle to increment
6
>> fh2(); % Invoke the second handle to increment
-1
Notice that these two different counters operate independently. The function handles fh and fh2 point to different instances of the function increment with different workspaces containing unique values for count.
In addition to the above, using function handles in conjunction with nested functions can also help streamline GUI design, as I illustrate in this other SO post.
Function handles are an extremely powerful tool in matlab. A good start is to read the online help, which will give you far more than I can. At the command prompt, type
doc function_handle
A function handle is a simple way to create a function in one line. For example, suppose I wished to numerically integrate the function sin(k*x), where k has some fixed, external value. I could use an inline function, but a function handle is much neater. Define a function
k = 2;
fofx = #(x) sin(x*k);
See that I can now evaluate the function fofx at the command line. MATLAB knows what k is, so we can use fofx as a function now.
fofx(0.3)
ans =
0.564642473395035
In fact, we can pass fofx around, effectively as a variable. For example, lets call quad to do the numerical integration. I'll pick the interval [0,pi/2].
quad(fofx,0,pi/2)
ans =
0.999999998199215
As you can see, quad did the numerical integration. (By the way, an inline function would have been at least an order of magitude slower, and far less easy to work with.)
x = linspace(0,pi,1000);
tic,y = fofx(x);toc
Elapsed time is 0.000493 seconds.
By way of comparison, try an inline function.
finline = inline('sin(x*k)','x','k');
tic,y = finline(x,2);toc
Elapsed time is 0.002546 seconds.
A neat thing about a function handle is you can define it on the fly. Minimize the function cos(x), over the interval [0,2*pi]?
xmin = fminbnd(#(x) cos(x),0,2*pi)
xmin =
3.14159265358979
There are many, many other uses for function handles in MATLAB. I've only scratched the surface here.
Disclaimer: code not tested...
The function handle operator allows you to create a reference to a function and pass it around just like any other variable:
% function to add two numbers
function total = add(first, second)
total = first + second;
end
% this variable now points to the add function
operation = #add;
Once you've got a function handle, you can invoke it just like a regular function:
operation(10, 20); % returns 30
One nice thing about function handles is that you can pass them around just like any other data, so you can write functions that act on other functions. This often allows you to easily separate out business logic:
% prints hello
function sayHello
disp('hello world!');
end
% does something five times
function doFiveTimes(thingToDo)
for idx = 1 : 5
thingToDo();
end
end
% now I can say hello five times easily:
doFiveTimes(#sayHello);
% if there's something else I want to do five times, I don't have to write
% the five times logic again, only the operation itself:
function sayCheese
disp('Cheese');
end
doFiveTimes(#sayCheese);
% I don't even need to explicitly declare a function - this is an
% anonymous function:
doFiveTimes(#() disp('do something else'));
The Matlab documentation has a fuller description of the Matlab syntax, and describes some other uses for function handles like graphics callbacks.