How to use function by having its name as a string - string

Suppose you want to use a sequence of functions defined in MATLAB, and you just have the name of those functions as string variables. Let say you have already created fun1, fun2, ...,funN, and you also have a vector of strings as ['fun1','fun2',...,'funN']. How to call each function automatically without being forced to write name of each function one by one?

Use str2func. Of course, if the functions have been defined as function handles (e.g. fun1 = #(x)x+x.^2+sqrt(x))), you can skip the str2func step below.
strList= {'sum','mean','max','min'};
funList = cellfun(#str2func,strList,'uniformOutput',false);
nFunctions = length(funList);
data = rand(10,1);
results = zeros(nFunctions,1)
for iFunction = 1:nFunctions
results(iFunction) = fulList{iFunction}(data);
end

Related

Split a string by some separaator

Let say I have below dummy code
import a_package as ap
calc = ap.func.func1()
So in my case calc is a function or method. However I want python to consider this as a string and split that based . and then return the last element i.e. return func1.
Is there any direct way to achieve the same?
As the other reviewers noted, you will need to start with a string if you want to perform a string operation. Assuming you have a way of getting a string in the form you showed, here are two examples of how to get the part of that string you are interested in:
import re
my_string = "ap.func.func1()"
# Should be sufficient for the use case you describe
my_split_string = s.split(".")
print(my_split_string[-1])
# More powerful (but more complex) if you have extended use cases
match = re.search(r"\.([^.]+)$", my_string)
print(match.group(1))
func1()
func1()

Pass by Reference in Haskell?

Coming from a C# background, I would say that the ref keyword is very useful in certain situations where changes to a method parameter are desired to directly influence the passed value for value types of for setting a parameter to null.
Also, the out keyword can come in handy when returning a multitude of various logically unconnected values.
My question is: is it possible to pass a parameter to a function by reference in Haskell? If not, what is the direct alternative (if any)?
There is no difference between "pass-by-value" and "pass-by-reference" in languages like Haskell and ML, because it's not possible to assign to a variable in these languages. It's not possible to have "changes to a method parameter" in the first place in influence any passed variable.
It depends on context. Without any context, no, you can't (at least not in the way you mean). With context, you may very well be able to do this if you want. In particular, if you're working in IO or ST, you can use IORef or STRef respectively, as well as mutable arrays, vectors, hash tables, weak hash tables (IO only, I believe), etc. A function can take one or more of these and produce an action that (when executed) will modify the contents of those references.
Another sort of context, StateT, gives the illusion of a mutable "state" value implemented purely. You can use a compound state and pass around lenses into it, simulating references for certain purposes.
My question is: is it possible to pass a parameter to a function by reference in Haskell? If not, what is the direct alternative (if any)?
No, values in Haskell are immutable (well, the do notation can create some illusion of mutability, but it all happens inside a function and is an entirely different topic). If you want to change the value, you will have to return the changed value and let the caller deal with it. For instance, see the random number generating function next that returns the value and the updated RNG.
Also, the out keyword can come in handy when returning a multitude of various logically unconnected values.
Consequently, you can't have out either. If you want to return several entirely disconnected values (at which point you should probably think why are disconnected values being returned from a single function), return a tuple.
No, it's not possible, because Haskell variables are immutable, therefore, the creators of Haskell must have reasoned there's no point of passing a reference that cannot be changed.
consider a Haskell variable:
let x = 37
In order to change this, we need to make a temporary variable, and then set the first variable to the temporary variable (with modifications).
let tripleX = x * 3
let x = tripleX
If Haskell had pass by reference, could we do this?
The answer is no.
Suppose we tried:
tripleVar :: Int -> IO()
tripleVar var = do
let times_3 = var * 3
let var = times_3
The problem with this code is the last line; Although we can imagine the variable being passed by reference, the new variable isn't.
In other words, we're introducing a new local variable with the same name;
Take a look again at the last line:
let var = times_3
Haskell doesn't know that we want to "change" a global variable; since we can't reassign it, we are creating a new variable with the same name on the local scope, thus not changing the reference. :-(
tripleVar :: Int -> IO()
tripleVar var = do
let tripleVar = var
let var = tripleVar * 3
return()
main = do
let x = 4
tripleVar x
print x -- 4 :(

How to convert a string to non string in matlab

I have this function which takes a string as an input.
for example it takes handles.f = 'x^2'
but I want handles.f = x^2 so that later I'll be able to do f(x) = handles.f
function edit1_Callback(hObject, eventdata, handles)
handles.f = (get(hObject,'String'))
handles.f
area = rect(handles.f,handles.u,handles.l,handles.n)
guidata(hObject,handles)
Function:
function [ s ] = rect( f,u,l,n )
syms x;
f(x) = f;
h =(u-l)/n
z = l:h:u;
y = f(z)
s = 0;
for i=1:n
s = s+y(i);
end
s = h*s;
end
When i call this function from command prompt like this:
rect(x^2,5,1,4)
It works fine
But it gives error when I call this from gui.
This is the error I get:
Error using sym/subsindex (line 1558)
Indexing input must be numeric, logical or ':'.
Error in rect (line 8)
f(x) = f;
This goes against any advice I give myself, but if you want to do what you're asking, you'll need to use eval. This converts any string that you input into it and it converts it into a command in MATLAB for you to execute. If I am interpreting what you want correctly, you want to make an anonymous function that takes in x as an input.
Therefore, you would do this:
handles.f = eval(['#(x) ' get(hObject,'String')]);
This takes in the string stored in hObject, wraps it into an anonymous function, and stores it into handles.f. As such, you can now do:
out = handles.f(x);
x is an input number. This is one of the few cases where eval is required. In general, I would not recommend using it because when code gets complicated, placing a complicated command as a string inside eval reduces code readability. Also, code evaluated in eval is not JIT accelerated... and it's simply bad practice.
Edit
Luis Mendo recommends doing str2func to avoid eval... which is preferable (whew!).
So do:
handles.f = str2func(['#(x) ' get(hObject,'String')]);

Question related to string

I have two statements:
String aStr = new String("ABC");
String bStr = "ABC";
I read in book that in first statement JVM creates two bjects and one reference variable, whereas second statement creates one reference variable and one object.
How is that? When I say new String("ABC") then It's pretty clear that object is created.
Now my question is that for "ABC" value to we do create another object?
Please clarify a bit more here.
Thank you
You will end up with two Strings.
1) the literal "ABC", used to construct aStr and assigned to bStr. The compiler makes sure that this is the same single instance.
2) a newly constructed String aStr (because you forced it to be new'ed, which is really pretty much non-sensical)
Using a string literal will only create a single object for the lifetime of the JVM - or possibly the classloader. (I can't remember the exact details, but it's almost never important.)
That means it's hard to say that the second statement in your code sample really "creates" an object - a certain object has to be present, but if you run the same code in a loop 100 times, it won't create any more objects... whereas the first statement would. (It would require that the object referred to by the "ABC" literal is present and create a new instance on each iteration, by virtue of calling the constructor.)
In particular, if you have:
Object x = "ABC";
Object y = "ABC";
then it's guaranteed (by the language specification) than x and y will refer to the same object. This extends to other constant expressions equal to the same string too:
private static final String A = "a";
Object z = A + "BC"; // x, y and z are still the same reference...
The only time I ever use the String(String) constructor is if I've got a string which may well be backed by a rather larger character array which I don't otherwise need:
String x = readSomeVeryLargeString();
String y = x.substring(5, 10);
String z = new String(y); // Copies the contents
Now if the strings that y and x refer to are eligible for collection but the string that z refers to isn't (e.g. it's passed on to other methods etc) then we don't end up holding all of the original long string in memory, which we would otherwise.

How can I create function pointers from a string input in MATLAB?

If I use the inline function in MATLAB I can create a single function name that could respond differently depending on previous choices:
if (someCondition)
p = inline('a - b','a','b');
else
p = inline('a + b','a','b');
end
c = p(1,2);
d = p(3,4);
But the inline functions I'm creating are becoming quite epic, so I'd like to change them to other types of functions (i.e. m-files, subfunctions, or nested functions).
Let's say I have m-files like Mercator.m, KavrayskiyVII.m, etc. (all taking a value for phi and lambda), and I'd like to assign the chosen function to p in the same way as I have above so that I can call it many times (with variable sized matrices and things that make using eval either impossible or a total mess).
I have a variable, type, that will be one of the names of the functions required (e.g. 'Mercator', 'KavrayskiyVII', etc.). I figure I need to make p into a pointer to the function named inside the type variable. Any ideas how I can do this?
Option #1:
Use the str2func function (assumes the string in type is the same as the name of the function):
p = str2func(type); % Create function handle using function name
c = p(phi, lambda); % Invoke function handle
NOTE: The documentation mentions these limitations:
Function handles created using str2func do not have access to variables outside of their local workspace or to nested functions. If your function handle contains these variables or functions, MATLABĀ® throws an error when you invoke the handle.
Option #2:
Use a SWITCH statement and function handles:
switch type
case 'Mercator'
p = #Mercator;
case 'KavrayskiyVII'
p = #KavrayskiyVII;
... % Add other cases as needed
end
c = p(phi, lambda); % Invoke function handle
Option #3:
Use EVAL and function handles (suggested by Andrew Janke):
p = eval(['#' type]); % Concatenate string name with '#' and evaluate
c = p(phi, lambda); % Invoke function handle
As Andrew points out, this avoids the limitations of str2func and the extra maintenance associated with a switch statement.

Resources