Pointer to MATLAB function? - 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

Related

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.

Passing additional arguments through function handle in Matlab

I have a function to optimize, say Function, in Matlab. This function depends on variables (say x) over which I want to optimize and one parameter (say, Q) which does not need to be optimized.Hence, the function Function(x,Q). In other words, I have an array of values for Q and want to find optimal x values for each Q. However, I cannot find a way how to pass those Q values when using function handle #Function in optimization function.
So, my question is how to pass those Q values when using function handle in optimization functions, for example fmincon(#Function,x0,A,b)?
Try using anonymous function:
x = cell( 1, numel(Q) );
for qi = 1:numel( Q )
x{qi} = fmincon( #(x) Function(x, Q(qi)), A, b );
end
As described in MATLAB documentation, there are actually 3 solutions for this problem:
Anonymous Functions
which is described in the Shai's answer of this post.
Nested Functions:
in this approach the outer function accepts all arguments, and the inner function only accepts parameters that optimization takes place on them.
this is an example taken from MATLAB documentation:
function [x,fval] = runnested(a,b,c,x0)
[x,fval] = fminunc(#nestedfun,x0);
% Nested function that computes the objective function
function y = nestedfun(x)
y = (a - b*x(1)^2 + x(1)^4/3)*x(1)^2 + x(1)x(2) +...
(-c + cx(2)^2)*x(2)^2;
end
end
Global Variables
in this approach you should define the parameters that are needed in objective function as global in workspace, and use them in objective function with declaring them as global.
here is an example again from MATLAB documentation:
Defining objective function:
function y = globalfun(x)
global a b c
y = (a - b*x(1)^2 + x(1)^4/3)*x(1)^2 + x(1)x(2) + ...
(-c + cx(2)^2)*x(2)^2;
end
Optimization:
global a b c;
a = 4; b = 2.1; c = 4; % Assign parameter values
x0 = [0.5,0.5];
[x,fval] = fminunc(#globalfun,x0)
You may be able to do the following:
x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon,options,Q)
which will pass Q along to fun(x,Q)!

MATLAB function syntax within script?

Having some trouble declaring functions within my script:
%Read the raw audio data
refData = wavread('file1.wav');
userData = wavread('file2.wav');
% I want to continue writing my "main" function here, and call the below functions
%%%%%%%%%%%%%
% Functions %
%%%%%%%%%%%%%
%Vector x
function preEmphasis(x)
alpha = 0.95;
len = length(x);
for i=1:len
x_i = x(i);
x_iMinus1 = x(i-1);
x(i) = x_i - alpha*x_iMinus1;
end
end
%Vector x
function normalization(x)
maxVal = max(abs(x));
x = x / maxVal;
end
%Vector x; numFrames, frameSize: integers; stepSize: percentage (float, 0.2 -> 0.5 for example)
function Ymatrix = createYmatrix(x, numFrames, frameSize, stepSize)
Ymatrix = zeros(numFrames, frameSize);
for i=1:numFrames
for j=1:frameSize
Ymatrix(i,j) = x(stepSize*i + j);
end
end
end
The words "function" and "end" are highlighted in red as "parse errors". How can I fix this? Thanks.
You can't declare functions within your main script. You have to create an external m-file and implement your function inside it, like it says in the official documentation:
Any function that is not anonymous must be defined within a file.
(just to be clear, a script does not accept input arguments or return output arguments).
However, you can have local functions declared inside a function m-file.
Read more about function declarations in the official documentation.
EDIT: You can Refer to #natan's answer if you're looking for a way to avoid function m-files altogether. He implemented your functions as anonymous functions, which can be declared inside the script file. Good luck!
In Addition to what Eitan mentioned, here is how to implement an anonymous functions in your case, note that code vectorization is a must. For example, in your case instead of normalization you can write:
normalization = #(x) x./max(abs(x));
and then use it as if it was a function, y=normalization(x)
For preEmphasis:
preEmphasis= #(x) [x(1) x(2:end)-0.95*x(1:end-1)];
Your current code has a bug for the case i=1 so I interpret that as for=2:len instead;
The solution for Ymatrix is a bit ugly (haven't invested to much time vectorizing it nicely), but it should work:
Ymatrix = #(x, numFrames, frameSize, stepSize) ...
ones(1,numFrames)'*x(1+stepSize:stepSize+frameSize)+...
meshgrid(0:stepSize:stepSize*numFrames-1,ones(1,frameSize))';
Just turn your script into a function; then you can use local and nested functions. Use return values or assignin if you need to get values back in to the base or caller's workspace.

MATLAB return of vector function with IF statement

I am calling a self written function 'func' of a vector like this:
x_values=[0 1 2];
result=func(x_values);
The problem is that in this function i have an if statement to determine the ouput. If I apply this function to a scalar, I have no problem, but if I apply it to a vector of numbers, the if statement doesn't do his job. why? And how can i repair it?
function [y]=func(x)
if(x==0)
y=0
else
y=1./sin(x);
end
end
You need to treat the zero and non-zero entries separately. This is easily achieved via indexing:
function [y]=func(x)
xIsZero = x==0;
%# preassign y
y = x;
%# fill in values for y
y(xIsZero) = 0
y(~xIsZero) = 1./sin(x(~xIsZero))
The answer is explained in the help document of IF:
An evaluated expression is true when the result is nonempty and
contains all nonzero elements (logical or real numeric). Otherwise,
the expression is false.
Conclusion: either add a for loop, or find a better way to vectorize your expression
You want to assign only a subset of the vector. For example:
function [y]=func(x)
y=zeros(size(x));
mask = x ~= 0;
y(mask) = 1 ./ sin(x(mask));
end

Adding an arbitrary number of functions into a function handle MATLAB

I'm trying to generate .bmp graphics in MATLAB and I'm having trouble summing functions together. I'm designing my function such that given an arbitrary set of inputs, my function will add an arbitrary number of functions together and output a function handle. The inputs are coefficients to my general function so I can specify any number of functions (that only differ due to their coefficients) and then add them together into a function handle. What I've tried to do is create each function as a string and then concatenate them and then write them as a function handle. The main problem is that because x and y aren't defined (because I'm trying to create a function handle) MATLAB can't add them regularly. My current attempt:
function HGHG = anyHGadd(multi) %my array of inputs
m=length(multi);
for k=3:3:m;
m1=multi(k-2); %these three are the coefficients that I'd like to specify
n1=multi(k-1);
w1=multi(k);
HGarrm1=hermite(m1); %these generate arrays
HGarrn1=hermite(n1);
arrm1=[length(HGarrm1)-1:-1:0];%these generate arrays with the same length
arrn1=[length(HGarrn1)-1:-1:0];%the function below is the general form of my equation
t{k/3}=num2str(((sum(((sqrt(2)*x/w1).^arrm1).*HGarrm1))*(sum(((sqrt(2)*y/w1).^arrn1).*HGarrn1))*exp(-(x^2+y^2)/(w1^2))));
end
a=cell2mat(t(1:length(t)));
str2func(x,y)(a);
Any help would be much appreciated. I haven't seen much on here about this, and I'm not even sure this is entirely possible. If my question isn't clear, please say so and I'll try again.
Edit: The fourth from last line shouldn't produce a number because x and y aren't defined. They can't be because I need them to be preserved as a part of my function handle. As for a stripped down version of my code, hopefully this gets the point across:
function HGHG = anyHGadd(multi) %my array of inputs
m=length(multi);
for k=3:3:m;
m1=multi(k-2); %these three are the coefficients that I'd like to specify
n1=multi(k-1);
w1=multi(k);
t{k/3}=num2str(genericfunction(x,y,n1,m1,n1,w1); %where x and y are unspecified
end
a=cell2mat(t(1:length(t)));
str2func(x,y)(a);
Edit I am expecting this to output a single function handle that is the sum of an arbitrary number of my functions. However, I'm not sure if using strings would be the best method or not.
Your question is not very clear to me, but I think you are trying to create a function that generate output functions parametrized by some input.
One way is to use closures (nested function that access its parent function workspace). Let me illustrate with an example:
function fh = combineFunctions(funcHandles)
%# return a function handle
fh = #myGeneralFunction;
%# nested function. Implements the formula:
%# f(x) = cos( f1(x) + f2(x) + ... + fN(x) )
%# where f1,..,fN are the passed function handles
function y = myGeneralFunction(x)
%# evaluate all functions on the input x
y = cellfun(#(fcn) fcn(x), funcHandles);
%# apply cos(.) to the sum of all the previous results
%# (you can make this any formula you want)
y = cos( sum(y) );
end
end
Now say we wanted to create the function #(x) cos(sin(x)+sin(2x)+sin(5x)), we would call the above generator function, and give it three function handles as follows:
f = combineFunctions({#(x) sin(x), #(x) sin(2*x), #(x) sin(5*x)});
Now we can evaluate this created function given any input:
>> f(2*pi/5) %# evaluate f(x) at x=2*pi/5
ans =
0.031949
Note: The function returned will work on scalars and return a scalar value. If you want it vectorized (so that you can apply it on whole vector at once f(1:100)), you'll have to set UniformOutput to false in cellfun, then combine the vectors into a matrix, sum them along the correct dimension, and apply your formula to get a vector result.
If your goal is to create a function handle that sums the output of an arbitrary number functions, you can do the following:
n = 3; %# number of function handles
parameters = [1 2 4];
store = cell(2,3);
for i=1:n
store{1,i} = sprintf('sin(t/%i)',parameters(i));
store{2,i} = '+'; %# operator
end
%# combine such that we get
%# sin(t)+sin(t/2)+sin(t/4)
funStr = ['#(t)',store{1:end-1}]; %# ignore last operator
functionHandle = str2func(funStr)
functionHandle =
#(t)sin(t/1)+sin(t/2)+sin(t/4)