Function names and parameters in matlab variables - matlab

In my matlab m-file I am using some logic (string concat) to build variables like this:
c = 'CalcPrediction(1,10)'
That means I have a string that is a function and some parameters. How can I do that function call?
Trying run(c) results in:
>> run(c)
??? Error using ==> run at 71
CalcPrediction(1,10) not found.
Note: run(c) works fine if there is no parameters. E.g.
c='CalcPrediction';
run(c);

The command you are looking for is eval() instead of run()

Without actually seeing the script it's hard to generalize, but...
Where squareRoot is an m-file containing only :y=sqrt(x)
Then executing :
x=[2,0];
c='squareRoot';
run(c);
gives :
y =
1.4142 0
This example is to say you can define the script to use a declared variable (x in this case) and then declare the variable before running the script.
Without the script I don't know what you're doing with the parameters. If this doesn't answer your question, post your script.

You want to use str2func. This function takes a string and returns a function handler that can be called with your parameters. Check out the examples on the linked page.
fh = str2func('CalcPrediction')
fh(1, 10)

Related

Command syntax for matlab function still generates output?

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();.

MATLAB: Access variables of a script in a function

This is a very basic question, but somehow, I am struck up with this.
Suppose there is a script
Script1.m
a = 1;
b = 2;
function1()
And a function, function1 in function1.m
function1.m
a = a/b;
end
Now when I run this, I get an error: 'Undefined function or variable "a".
I am familiar with C/C++, and I know that I can pass a, b as arguments to the function. But suppose 'a' contains a lot of data , which if passed through the function would consume a lot of time. So it won't be feasible to pass the variable.
Is there any other approach to achieve the same?
Edit 1:
Suppose I am using Pattern Search, or some other function which takes a function1 handle as an argument, then how do I pass variables local to script1 to function1.

MATLAB Beginner recursive functions

Just having a little difficulty with the syntax of matlab functions;
function f = fact(x)
if x == 1
return
else
f = 1 - x*(fact(x-1))
end
end
When calling this function in the command window with the argument 10 I receive the error
Undefined function 'fact' for input arguments of type 'double'.
Error in recursion (line 6)
f = 1 - x*(fact(x-1))
I've had a look around and solutions for the first revolve around the pathing of the m-file which doesn't seem to be a problem as other files in the same directory run fine,
The second I'm not sure why the error in line 6 occurs, my guess is it has something to do with the variable and function names.
As a side question, are both these end statements necessary?
Thanks!
The most obvious error is your function filename. You have a function called fact defined in your code but you named your file recursion. Make sure that both your function name and the filename are both called fact.
If you were to name your file as recursion, then make the function name defined in your code as fact, this is what would happen if you tried calling your code:
>> f = recursion(10);
Undefined function 'fact' for input arguments of type 'double'.
Error in recursion (line 6)
f = 1 - x*(fact(x-1));
... look familiar?
As such make sure your filename and your function name are named the same. In fact, in the MATLAB editor, it should automatically give you an error saying that both of these are not the same.
There is also another error in your code. The base case is not defined properly. Always remember when you are writing recursive algorithms is that eventually the function is going to return... and that's when you hit the base case. We can see here that it is when x = 1. When x = 1, you're supposed to assign something to f which is the output. You are simply exiting the function, and so when x becomes 1, your code will spit out an error saying that f was not assigned when the function finishes. As such, you need to figure out what your base case is. I'm going to assume that your base case (when x = 1) is going to equal 0. You will obviously need to change this as I don't know what your code is actually computing. Basically, you need to do this:
function f = fact(x)
if x == 1
f = 0; %// Base case needs to change according to your specs
else
f = 1 - x*(fact(x-1))
end
end
When I do this, I get the following output when x = 10
>> f = fact(10);
f =
1334961
I don't get an error when I run this code now. Also, check to see if you have any variables named fact in your workspace. When this happens, you are in fact shadowing over your function with a variable, so it is actually trying to access the variable called fact instead. As such, try clearing your workspace by doing clear all;, then try this code again.
One warning
If you were to specify x to be 0 or negative, this function will never stop. As such, you need to provide some check and perform the proper action when this happens. Also, you need to make sure that you specify what type of inputs are accepted for x. Judging from the context, x are positive integers only. As what #Glen_b has noted, should you provide any number that isn't a positive integer, this function will never stop as x will never equal 1 down the recursion pipeline.
To answer your optional question
The first end statement is required to end the if statement. The second end statement isn't required, but it's good practice anyway. However, if you have multiple functions defined inside your function file, then yes it is most definitely required to properly signify that the end of that function is defined there. However, you don't need it if you're only writing one function per file, but I would recommend keeping it there as it's good practice.

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

Picking out the fourth value of a function using an anonymous function [duplicate]

I have a function that returns two values, like so:
[a b] = myfunc(x)
Is there a way to get the second return value without using a temporary variable, and without altering the function?
What I'm looking for is something like this:
abs(secondreturnvalue(myfunc(x)))
not that i know of. subsref doesn't seem to work in this case, possibly because the second variable isn't even returned from the function.
since matlab 2009b it is possible to use the notation
[~, b] = function(x)
if you don't need the first argument, but this still uses a temporary variable for b.
Unless there is some pressing need to do this, I would probably advise against it. The clarity of your code will suffer. Storing the outputs in temporary variables and then passing these variables to another function will make your code cleaner, and the different ways you could do this are outlined here: How to elegantly ignore some return values of a MATLAB function?.
However, if you really want or need to do this, the only feasible way I can think of would be to create your own function secondreturnvalue. Here's a more general example called nth_output:
function value = nth_output(N,fcn,varargin)
[value{1:N}] = fcn(varargin{:});
value = value{N};
end
And you would call it by passing as inputs 1) the output argument number you want, 2) a function handle to myfunc, and 3) whatever input arguments you need to pass to myfunc:
abs(nth_output(2,#myfunc,x))