MATLAB str2func to send function - function

I want to pass function(string) from uicontrol via my GUI, and how properly use str2func to send function into my m file.
Piece of my GUI.m file
function functionbox_Callback(hObject, eventdata, handles)
fun= str2func(get(handles.functionbox, 'String'));
[x, y] = hessian(fun);
Piece of my hessian.m file where i want to pass function from GUI:
function [x, y] = hessian(fun)
f = #(x,y) fun;
blablabla
hold off
How I can do this kind of method.

If I understood correctly your question you have pretty much figured it out. What is missing from your code would be to call f with appropriate input arguments to obtain the outputs x and y.
Consider this code which is based on yours. The use enters a function in the lefthand box and the output (actually x+y...just for the demo) is displayed in the righthand box. Play around with it too see how the functions work together. Please ask if something is unclear.
Code:
function LoadFun
clear
clc
hfigure = figure('Position',[200 200 300 300]);
handles.TextFunction = uicontrol('Style','Text','Position',[20 220 100 20],'String','Enter function');
handles.functionbox = uicontrol('Style','edit','Position',[20 200 100 20],'String','');
handles.TextResult = uicontrol('Style','Text','Position',[140 220 100 20],'String','Output');
handles.resultbox = uicontrol('Style','edit','Position',[140 200 100 20],'String','');
handles.Button = uicontrol('Style','push','Position',[20 160 100 20],'String','Call function','Callback',#(s,e) ButtonCallback);
%// Call the function
function ButtonCallback
fun= str2func(get(handles.functionbox, 'String'));
[x,y] = hessian(fun);
%// Make other calculation and display output;
z = x+y;
set(handles.resultbox ,'String',num2str(z));
end
%// Your function
function [x,y] = hessian(fun)
%// Define handles. Inputs do not have to be x and y here.
f = #(a,b) fun(a) + fun(b);
%// Perform operations
x = f(pi,pi/2);
y = f(0,2*pi);
end
end
Screenshot:
Hope that is what you were after!

str2func works a lot like the function-handle #.
So if your input looks something like this:
'#(x,y) x+y'
or
'functionname'
it should work just fine.
To pass the, now, function handle to your GUI, you do not need to define it again:
function [x, y] = hessian(fun)
result=fun(data);
blablabla hold off
As for multiple Outputs of anonymous-functions:
it is possible, but, as far as I know, not inline.
Source:http://ch.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html#f4-70159
But this is easily solved with arrays.

Related

Scilab - define a function inside another one

I want to define a function that takes an input n and gives back the function f defined by f(x) = x^n.
So I wrote the following piece of code on Scilab:
function [f]=monomial(n)
function [z] = g(x)
z = x^n
endfunction
f = g
endfunction
Unfortunately when I evaluate monomial(3)(2) I get 32. whereas it should be 8.
I hope someone could point out where I have gone wrong when writing this function.
Could somebody help me please?
I cleared all variables and reran the code and it told me that n is not defined within g, therefore is there a way to overcome this problem?
the more secure way to do this is by using deff :
function [f]=monomial(n)
f = deff('z=g(x)','z=x^'+string(n));
endfunction
otherwise n could be polluted by current scope
--> monomial(2)(8)
ans =
64.

Scilab not returning variables in variable window

I have created a function that returns the magnitude of a vector.the output is 360x3 dimension matrix. the input is 360x2.
Everything works fine outside the function. how do i get it to work ?
clc
P_dot_ij_om_13= rand(360,2); // 360x2 values of omega in vectors i and j
//P_dot_ij_om_13(:,3)=0;
function [A]=mag_x(A)
//b="P_dot_ijOmag_"+ string(k);
//execstr(b+'=[]'); // declare indexed matrix P_dot_ijOmag_k
//disp(b)
for i=1:1:360
//funcprot(0);
A(i,3)=(A(i,2)^2+A(i,1)^2)^0.5; //calculates magnitude of i and j and adds 3rd column
disp(A(i,3),"vector magnitude")
end
funcprot(1);
return [A] // should return P_dot_ijOmag_k in the variable browser [360x3 dim]
endfunction
mag_x(P_dot_ij_om_13);
//i=1;
//P_dot_ij_om_13(i,3)= (P_dot_ij_om_13(i,2)^2+P_dot_ij_om_13(i,1)^2)^0.5;// example
You never assigned mag_x(P_dot_ij_om_13) to any variable, so the output of this function disappears into nowhere. The variable A is local to this function, it does not exist outside of it.
To have the result of calculation available, assign it to some variable:
res = mag_x(P_dot_ij_om_13)
or A = mag_x(P_dot_ij_om_13) if you want to use the same name outside of the function as was used inside of it.
By the way, the Scilab documentation discourages the use of return, as it leads to confusion. The Scilab / Matlab function syntax is different from the languages in which return specifies the output of a function:
function y = sq(x)
y = x^2
endfunction
disp(sq(3)) // displays 9
No need for return here.

Writing a function m-file in MATLAB

I am a beginner to coding and I need to write a function.m file for use with Newton's Method. I am having trouble defining the function, where r is radius and p is density:
f(theta) = ((r^2)/2)*((2*pi*p)-(theta - sin(theta)*p))
where radius r = 30cm and density p = 0.82 grams per cm^3
So far, I have written:
function y = f1(theta)
r = 0.3;
p = 0.82;
y = (r^2)/2*(2*pi*p - (theta - sin(theta)*p));
Things I am having trouble with:
Problem defining r and p. Getting an error:
Undefined function or variable 'r'
Having trouble plotting the function.
Things I want to do:
Plot the function to see where the roots are.
Be able to evaluate the function for a given theta.
All help is appreciated. Thank you!
i tried your code without changing. i named the M-file as f1 and executed the function in command line it is working.
function y = f1(theta)
r = 0.3;
p = 0.82;
y = (r^2)/2*(2*pi*p - (theta - sin(theta)*p));
i am getting the output as below
f=f1(45)
f =
-1.7618
this tells that there is no problem in your function. see for some other reason. if you could give your whole code it would be better to diagnose.
This could be done using an anonymous function
r=0.3;
p=0.82;
f=#(theta) (r^2)/2*(2*pi*p-theta+p*sin(theta));
then to evaluate the function just use eg: f(1), and to plot it, for example:
angles=0:.01:pi;
plot(angles,f(angles))
If you don't want to use an anonymous function, then use
function funcVal=func(angles)
r=0.3;
p=0.82;
funcVal=(r^2)/2*(2*pi*p-angles+p*sin(angles));
end
and call it by
angles=0:.01:pi;
plot(angles,func(angles))

Random Number Functions Python

I am making a little game where when events happen, rectangles get spawned at a random x and y point and I am having some trouble implementing functions into this. Here is some basic code:
xran = random.randint(5, 485)
yran = random.randint(5, 485)
xran1 = random.randint(5, 450)
yran1 = random.randint(5, 400)
def allRand():
#This REGENERATES those randoms making it 'spawn' in a new location.
xran = random.randint(0, 485)
yran = random.randint(0, 485)
xran1 = random.randint(5, 450)
yran1 = random.randint(5, 400)
char = pygame.draw.rect(screen, black, (x,y,15,15), 0)
food = pygame.draw.rect(screen, green, (xran,yran,10,10), 0)
badGuy = pygame.draw.rect(screen, red, (xran1,yran1,50,100), 0)
if char.colliderect(food):
score += 1
print "Your score is:",score
allRand()
Does calling a function that regenerates random numbers work for any of you? I know it regenerates them because I have had it print back the variables, for some reason my rects don't do there though.
Note: This is just snippet of my code it was just meant to give an idea of what I am trying to do.
Thanks!
You need to declare xran, etc. with global inside the allRand() function. Otherwise, it's just creating new variables inside function scope, assigning them random values, then throwing them away when the function returns.
Your allRand() method doesn't have any code. You must indent the lines you want in that function.
It's kinda working because you still call those statements below your def. But it's not because you're calling the function.
To add to Lee Daniel Crocker's answer, when you create variables in a function they exist only in that function. If you want them to exist outside you can either make them global variables as he suggested, you are can return them and catch them:
>>> def square(number):
squared = number*number
return squared
>>> square(3)
9
>>> ninesquared = square(3)
>>> ninesquared
9
>>>
Read more
It looks like you need to master your basics. I suggest doing that first before trying things in pygame.
EDIT:
If you define variables outside of the function, they will not effect any variables you define in the function either.
>>> x = 5
>>> def rais():
x = 10
>>> x
5
>>> rais()
>>> x
5
>>>
Notice how rais did nothing?
If we change the line in rais to be x = x + 1 then python will give us back an error that x is not defined.
If you want you're variables to get into the function you need to pass them in as parameters, but once again, they won't effect anything outside of the function unless you return and capture them. And once again, you can declare them as global variables and that will also work.

Pointer to MATLAB function?

So I have a for-loop in MATLAB, where either a vector x will be put through one function, say, cos(x).^2, or a different choice, say, sin(x).^2 + 9.*x. The user will select which of those functions he wants to use before the for-loop.
My question is, I dont want the loop to check what the user selected on every iteration. Is there a way to use a pointer to a function, (user defined, or otherwise), that every iteration will use automatically?
This is inside a script by the way, not a function.
Thanks
You can use function_handles. For your example (to run on all available functions using a loop):
x = 1:10; % list of input values
functionList = {#(x) cos(x).^2, #(x) sin(x).^2 + 9*x}; % function handle cell-array
for i=1:length(functionList)
functionOut{i} = functionList{i}(x); % output of each function to x
end
You can try something like the following:
userChoice = 2;
switch userChoice
case 1
myFun = #(x) sin(x).^2 + 9.*x;
case 2
myFun = #(x) cos(x).^2;
end
for k = 1:10
x(k,:) = myFun(rand(1,10));
end