Command syntax for matlab function still generates output? - matlab

There are two ways to call functions in Matlab, the command syntax and function syntax.
I am viewing a code written by someone else in which there's a statement as follows in one .m file:
params=sys_params;
while sys_params is defined as a function in another .m file as:
function params=sys_params()
params happens to be a structure.
What I wish to know is, if according to Matlab documentation, a command syntax cannot be used to output from a function, then how is the first statement working perfectly well?

Two things:
The distinction between command and function syntax comes into play when arguments are passed.
The parentheses for calling a function in MATLAB are optional when calling with no arguments. MATLAB will call the function without an invoking () unlike some other languages.
One exception to this that comes to mind is that () is required to invoke a function handle/anonymous function.
From Calling Functions:
To call a function that does not require any inputs and does not return any outputs, type only the function name
The one ambiguous thing not explicitly told there is that assigning output of such a function call is perfectly valid.
I'll note that I don't really like that () is optional as it hides function calls at-first-glance. Therefore, I try to use () as often as possible to make it clear I am invoking a function, so nearly all of my scripts start with clc();clear();.

Related

Using the Python C API, how can I write a function that accepts any number of arguments, including none at all?

METH_VARARGS requires at least one argument; METH_NOARGS doesn't seem to let me pass any at all.
How can I define a function build() that can be called as either build() or build(True)/build(False)?
Calling a METH_VARARGS function with no arguments results in:
TypeError: function takes exactly 1 argument (0 given)
I was thinking about the problem wrong. It's not the definition, but rather the parsing that rose my TypeError.
To prevent it, I just had to use "|O" instead of "O" in PyArg_ParseTuple!

Does anonymous function requires lambda format (println ex)?

I got to know recently that Anonymous function
is given in the form of: function body that follows argument Lambda
(=>)
and it has no name
is used once in the code
So, you don't have to add a complete function to do this but rather, you can put the function body in use directly in your code (main function).
I read that in spark, "println" statement is always considered anonymous method for the following reasons:
println statement is considered a function body
Moreover, it wasn't added to a method with a name but was rather
used directly in the main class.
Also, it was used once in the code.
Ex:
Before converting to anonymous
click to view pic1
After converting to anonymous
click to view pic2
However, my question is what if the Lambda function wasn't used.. will println be considered as anonymous function still as shown in the ex below?
main question Ex:
click to view pic3
println is a function, but it is not an anonymous function since it has a name.

found a function in a file and after select it to do operation in my program matlab

I created this function to browse all the functions stored in a file and now I want to select my function in my main program how can I select it
This is my function:
function testMode(i)
a=dir('H_*.m');
if exist('i','var')
if isempty(i)
z={a.name}';
[selection,ok]=listdlg('ListString',z,'SelectionMode','single');
if ok
i=find(selection,1,'first');
end
end
nom=a(i).name;
nom=nom(1:end-2);
disp(nom)
else
disp('fonction a un argument')
end
It looks like you will have the name of the function as a string. To call that function, you can either use feval, or you can convert the string to a function handle and call that.
result = feval(nom, argument1);
or
fcn = str2func(nom);
fcn(argument1);
The latter should be preferred, as the conversion can be done once and the function handle re-used after that, and because the calling syntax is exactly the same as calling a regular function.
For more information on function handles, see doc function_handle.
Also, for a different approach, see this document: http://www.mathworks.com/help/matlab/ref/localfunctions.html. If you can create your "menu" of functions as local functions in a single file, this approach could be very clean and simple, as it will directly give you a cell array of function handles of all of those subfunctions. From there, you can get easily get the function name for display using functions command.

How to safely manipulate MATLAB anonymous functions in string form

I have an anonymous function that I would like to manipulate in string form then use with fsolve.
When I do this the references in the anonymous function to constants are lost and fsolve fails.
The problem is easily illustrated.
The following works:
A=3;
myfun=#(x)sin(A*x);
x = fsolve(#(x)myfun(x),[1 4],optimoptions('fsolve','Display','off'))
The following throws an error as explained here:
A=3;
myfun=#(x)sin(A*x);
mystring=func2str(myfun);
%string operations would go here such as strrep(mystring,'A','A^2') or whatever
myfun2=str2func(mystring);
x = fsolve(#(x)myfun2(x),[1 4],optimoptions('fsolve','Display','off'))
Is there some way I CAN safely manipulate an anonymous function while retaining references to constant parameters?
more info
Specifically I'm writing a simple wrapper to allow fsolve to accept imaginary numbers for simple cases. The following illustrates a working example without a constant parameter:
myeqn=#(x)0.5*x^2-5*x+14.5;
cX0=1+1*1i;
f1=strrep(func2str(myeqn),'#(x)','');
f2=strrep((f1),'x','(x(1)+(x(2))*1i)');
f3=strcat('#(x)[real(',f2,'); imag(',f2,')]');
fc=str2func(f3);
opts=optimoptions('fsolve','Display','off');
result=arrayfun(#(cinput)[1 1i]*(real(fsolve(fc,[real(cinput);imag(cinput)],opts))),cX0)
As in the failed example above if I include a parameter in my wrapper the process fails with the same error as above.
I originally suggested to use the symbolic math toolbox, but reading your question again I realized it's just a simple substitution of input parameters. You can achieve this using function handles without any string processing.
myeqn=#(x)0.5*x^2-5*x+14.5;
cX0=1+1*1i;
wrapper=#(x,f)([real(f(x(1)+x(2)*i)),imag(f(x(1)+x(2)*i))])
opts=optimoptions('fsolve','Display','off');
result=arrayfun(#(cinput)[1 1i]*(real(fsolve(#(x)wrapper(x,myeqn),[real(cinput);imag(cinput)],opts))),cX0)
As much as I hate to suggest using the eval function, you could do:
myfun2 = eval(mystring);
Using eval is kinda frowned upon because it makes code hard to analyze (since arbitrary nastiness could be going on in that string), but don't let other people's coding style stop you from doing what works :)
In your longer example, this would correspond to changing the line:
fc=str2func(f3);
to:
fc=eval(f3);
Again, the use of eval is strongly discouraged, so you should consider alternatives to this type of string manipulation of function definitions.

Declaring variables before declaring a function

Suppose I want to declare some variables then declare a function:
x = 2;
function y = function(x)
y = (x^2)+1;
end
y = function(x);
disp(y)
Matlab returns the error "Function keyword use is invalid here..."
Why can't I declare variables or write any text before declaring a function? Is there good reason or is it a quirk?
EDIT:
To clarify, I do know how to get around this problem (but thanks for the suggestions nonetheless) but I suppose I'm asking why the Matlab team made this decision. By making a function declaration the first line of a file, does it have implications for memory management, or something?
The REPL prompt of Scala can have a function defined after a variable. So this is a choice (a quirk if you want) from Matlab's inner internals.
If a function is defined in a file, there are two possibilities:
The main function of that file. Then the file must begin with the function declaration: in your example, function y = fun(x). I'm using fun as the function's name. I don't think function can be used as a function's name.
See here for more details.
A nested function. In this case, the function declaration and definition can be within another function of the preceding case.
See here for more details.
As you can see, in either case the file begins with a function declaration (namely that of the main function).
The function can also be defined as an anonymous function. Then no declaration is needed, and the function can be defined anywhere. But there's a restriction: the function can contain only a single statement (so it cannot define internal variables other than the output). Therefore this method can only be used for simple functions.
In your example, the function could be defined anonymously as fun = #(x) x^2+1.
See here for more details.
Others have given good info about nested functions and such.
But the reason for the error you get is that "function" is a reserved word in Matlab. You cannot have a function with this name.
function y = my_function(x)
y = (x^2)+1;
end
And stick it in another file called my_function.m