In Matlab, I generally do things such as
f = #(x) x.^2;
xx = 0:.1:1;
ff = f(xx);
So that f is a function handle and both xx and ff are 1x11 vectors.
However, if for some reason I need to define my function handle f like this
f = #(x) 1;
and do not change the code for xx and ff, then xx will still be a vector but ff will NOT: it will be a double.
This is annoying of course, because the sequel of my code assumes that ff is a 11x1 vector, so I would need to change my code any time f happens to be constant.
So my first question is whether or not my code is sound to begin with.
If so, what should I do to make it work in the "constant f" case?
If not, how should I rewrite it?
This is admittedly similar to
matlab constant anonymous function returns only one value instead of an array
but I can't quite find an answer in that thread.
A minor modification of the answer you linked will provide the required result:
f = #(x) ones(size(x));
The size of f(x) will match the size of the input x since f outputs a vector of ones the same size as x.
I found a better way of doing this. This shows how stupid Matlab is:
f = #(x) (x-x)+1
Try it!
Related
I write code to do optimization to solve a problem taking the form min_x f(x,c) s.t. sum(x)=1 and g(x,c)=1, where x is a vector and c is a function of x such that c(x) is a constant when x is fixed. Indeed, g(x,c) takes the following form
n=5; N=1000000; idx = 1:1:n; df=4; theta=2; alpha=2.4;
central_Simulation_Points=mvtrnd(eyes(n),df,N);
x=sym('x_%d',[n,1]); syms c
g(x,c)=1./N.*sum((theta.*(alpha-1).*central_Simulation_Points*x).^2+c).^(1./(alpha-1)))==1;
Constraint_equ = solve(g(x,c), c);
Constraint_equ_handle = matlabFunction(Constraint_equ);
The use of solve is to express c in terms of x, while matlabFunction changes the symbolic function to function handle for input. I then define an objective function obj_fun=#(x)f(x,c(x)). The objective function for optimization is
(alpha-1)/alpha*sum_{i=1}^N[(theta*(alpha-1)*V(x,Xi)+c)^(1/(alpha-1))*V(x,Xi)]+c/(theta*alpha*(1-alpha))
V(x,Xi) is any function. I use (x^{T}Xi)^2. Xi is the i-th row of central_Simulation_Points.
When I count the the time, Equ = 1./N.*sum((theta.*(alpha-1).*central_Simulation_Points*x).^2+c).^(1./(alpha-1)))==1; takes 203 seconds to run, but it seems that Constraint_equ = solve(Equ, c); never makes the program stops. I wonder if any other methods could be used instead of using
Constraint_equ = solve(Equ, c);
Constraint_equ_handle = matlabFunction(Constraint_equ);
Are there any ways to find c in terms of x, or any ways to modify the code?
Is it possible in Matlab to specify at function declaration that this specific function is to be applied to indiviual arguments (as opposed to vectors)? An if so, what about anonymous functions?
What I mean is, instead of writing something like
f = #(x, y) x.^2+2*x.*y.^2-x./(y.^3)...
One might be able to write something like
f = .#(x, y) x^2+2*x*y^2-x/y^3
This would help a lot light-headed people like me who tend to forget dots.
Sorry if it's a duplicate, I searched but as you can see I have trouble putting it in clear words so I cannot find an answer.
not sure if that does the trick for you, but you can but an arrayfun inside the anonymous function like:
f = #(x,y) x.^2+2*x.*y.^2-x./(y.^3);
g = #(x,y) arrayfun(#(A,B) A^2+2*A*B^2-A/B^3 ,x,y) %for matrix output
h = #(x,y) arrayfun(#(A,B) A^2+2*A*B^2-A/B^3 ,x,y,'UniformOutput',false); % for cell output
with A being an element of x and B being an element of y
We have an equation similar to the Fredholm integral equation of second kind.
To solve this equation we have been given an iterative solution that is guaranteed to converge for our specific equation. Now our only problem consists in implementing this iterative prodedure in MATLAB.
For now, the problematic part of our code looks like this:
function delta = delta(x,a,P,H,E,c,c0,w)
delt = #(x)delta_a(x,a,P,H,E,c0,w);
for i=1:500
delt = #(x)delt(x) - 1/E.*integral(#(xi)((c(1)-c(2)*delt(xi))*ms(xi,x,a,P,H,w)),0,a-0.001);
end
delta=delt;
end
delta_a is a function of x, and represent the initial value of the iteration. ms is a function of x and xi.
As you might see we want delt to depend on both x (before the integral) and xi (inside of the integral) in the iteration. Unfortunately this way of writing the code (with the function handle) does not give us a numerical value, as we wish. We can't either write delt as two different functions, one of x and one of xi, since xi is not defined (until integral defines it). So, how can we make sure that delt depends on xi inside of the integral, and still get a numerical value out of the iteration?
Do any of you have any suggestions to how we might solve this?
Using numerical integration
Explanation of the input parameters: x is a vector of numerical values, all the rest are constants. A problem with my code is that the input parameter x is not being used (I guess this means that x is being treated as a symbol).
It looks like you can do a nesting of anonymous functions in MATLAB:
f =
#(x)2*x
>> ff = #(x) f(f(x))
ff =
#(x)f(f(x))
>> ff(2)
ans =
8
>> f = ff;
>> f(2)
ans =
8
Also it is possible to rebind the pointers to the functions.
Thus, you can set up your iteration like
delta_old = #(x) delta_a(x)
for i=1:500
delta_new = #(x) delta_old(x) - integral(#(xi),delta_old(xi))
delta_old = delta_new
end
plus the inclusion of your parameters...
You may want to consider to solve a discretized version of your problem.
Let K be the matrix which discretizes your Fredholm kernel k(t,s), e.g.
K(i,j) = int_a^b K(x_i, s) l_j(s) ds
where l_j(s) is, for instance, the j-th lagrange interpolant associated to the interpolation nodes (x_i) = x_1,x_2,...,x_n.
Then, solving your Picard iterations is as simple as doing
phi_n+1 = f + K*phi_n
i.e.
for i = 1:N
phi = f + K*phi
end
where phi_n and f are the nodal values of phi and f on the (x_i).
my question relates to the Symbolic Math Toolbox from Matlab. I have the following code:
syms x x_0 u delta sigma_1
mu = sym ('mu(x)');
sigma_u = sym ('sigma(u)');
sigma = sym ('sigma(x)');
f = int (1/sigma_u, u, x_0, x);
df = subs(diff(f,x))
df_2 = subs(diff (f,x,2))
L = subs(mu*df+1/2*sigma^2*df_2)
The result of L is corect
L =
mu(x)/sigma(x) - diff(sigma(x), x)/2
However, for further derivations and for simplicity, I would like to define
sigma_1 = sym('diff(sigma,x)');
or in a similar way such as to get as result for
L =
mu(x)/sigma(x) - sigma_1(x)/2
Basically, I would like to store under a name the symbolic expression diff(sigma(x),x) such that Matlab knows that when it gets this result in a expression, to poste the name sigma_1 (x) instead of diff(sigma(x),x)
Yes it is possible, you can use subs(L, 'diff(sigma(x),x)', 'sigma_1(x)'). Note to make the substitution work, the second input of subs must be exactly like what you want to replace; hence it cannot be 'diff(sigma, x)' which lacks the (x) behind the sigma.
Also note that here is a similar question for which I provided a more complete solution (they asked the question after yours, but I read theirs first).
How can I make a function from a symbolic expression? For example, I have the following:
syms beta
n1,n2,m,aa= Constants
u = sqrt(n2-beta^2);
w = sqrt(beta^2-n1);
a = tan(u)/w+tanh(w)/u;
b = tanh(u)/w;
f = (a+b)*cos(aa*u+m*pi)+a-b*sin(aa*u+m*pi); %# The main expression
If I want to use f in a special program to find its zeroes, how can I convert f to a function? Or, what should I do to find the zeroes of f and such nested expressions?
You have a couple of options...
Option #1: Automatically generate a function
If you have version 4.9 (R2007b+) or later of the Symbolic Toolbox you can convert a symbolic expression to an anonymous function or a function M-file using the matlabFunction function. An example from the documentation:
>> syms x y
>> r = sqrt(x^2 + y^2);
>> ht = matlabFunction(sin(r)/r)
ht =
#(x,y)sin(sqrt(x.^2+y.^2)).*1./sqrt(x.^2+y.^2)
Option #2: Generate a function by hand
Since you've already written a set of symbolic equations, you can simply cut and paste part of that code into a function. Here's what your above example would look like:
function output = f(beta,n1,n2,m,aa)
u = sqrt(n2-beta.^2);
w = sqrt(beta.^2-n1);
a = tan(u)./w+tanh(w)./u;
b = tanh(u)./w;
output = (a+b).*cos(aa.*u+m.*pi)+(a-b).*sin(aa.*u+m.*pi);
end
When calling this function f you have to input the values of beta and the 4 constants and it will return the result of evaluating your main expression.
NOTE: Since you also mentioned wanting to find zeroes of f, you could try using the SOLVE function on your symbolic equation:
zeroValues = solve(f,'beta');
Someone has tagged this question with Matlab so I'll assume that you are concerned with solving the equation with Matlab. If you have a copy of the Matlab Symbolic toolbox you should be able to solve it directly as a previous respondent has suggested.
If not, then I suggest you write a Matlab m-file to evaluate your function f(). The pseudo-code you're already written will translate almost directly into lines of Matlab. As I read it your function f() is a function only of the variable beta since you indicate that n1,n2,m and a are all constants. I suggest that you plot the values of f(beta) for a range of values. The graph will indicate where the 0s of the function are and you can easily code up a bisection or similar algorithm to give you their values to your desired degree of accuracy.
If you broad intention is to have numeric values of certain symbolic expressions you have, for example, you have a larger program that generates symbolic expressions and you want to use these expression for numeric purposes, you can simply evaluate them using 'eval'. If their parameters have numeric values in the workspace, just use eval on your expression. For example,
syms beta
%n1,n2,m,aa= Constants
% values to exemplify
n1 = 1; n2 = 3; m = 1; aa = 5;
u = sqrt(n2-beta^2);
w = sqrt(beta^2-n1);
a = tan(u)/w+tanh(w)/u;
b = tanh(u)/w;
f = (a+b)*cos(aa*u+m*pi)+a-b*sin(aa*u+m*pi); %# The main expression
If beta has a value
beta = 1.5;
eval(beta)
This will calculate the value of f for a particular beta. Using it as a function. This solution will suit you in the scenario of using automatically generated symbolic expressions and will be interesting for fast testing with them. If you are writing a program to find zeros, it will be enough using eval(f) when you have to evaluate the function. When using a Matlab function to find zeros using anonymous function will be better, but you can also wrap the eval(f) inside a m-file.
If you're interested with just the answer for this specific equation, Try Wolfram Alpha, which will give you answers like:
alt text http://www4c.wolframalpha.com/Calculate/MSP/MSP642199013hbefb463a9000051gi6f4heeebfa7f?MSPStoreType=image/gif&s=15
If you want to solve this type of equation programatically, you probably need to use some software packages for symbolic algebra, like SymPy for python.
quoting the official documentation:
>>> from sympy import I, solve
>>> from sympy.abc import x, y
Solve a polynomial equation:
>>> solve(x**4-1, x)
[1, -1, -I, I]
Solve a linear system:
>>> solve((x+5*y-2, -3*x+6*y-15), x, y)
{x: -3, y: 1}