substituting my function in an expression - matlab

I have defined a function as mystep in matlab 2014b, which is the same as heaviside except for mystep(0) which is one instead of 0.5.
Now I would like to substitute my function using subs into an expression but it is not possible. Function is:
f(x) = heaviside(x) * x^2;
g(x) = subs(f(x) , heaviside(x) , mystep(x));
g(x) =
heaviside(x)
As you see, matlab does not do anything, but if I change mystep with dirac(x), it goes well.
g(x) = subs(f(x) , heaviside(x) , dirac(x))
g(x) =
dirac(x)
what should I do? is there any way to do this?
Any other help like showing a way to change the value of heaviside at origin in matlab 2014b might be useful.
The content of mystep
function Y = mystep(X)
%//This function is a user-defined unit step function, which has the exact
%//properties of matlab heaviside function except for the value of function
%//at zero that is defined as 1.
Y = heaviside(X);
if Y==0.5
Y=1;
end

Now I understand your problem. The mystep function you implemented is not compatible to symbolic math. If you try mystep(sym(x)) you will see it returns heaviside. That's because a symbolic variable compared to a constant is always false.
The best solution I see is to use this definition for mystep
syms x
mystep(x)=heaviside(x)+1/2-abs(heaviside(x)-.5);
g(x) = subs(f(x) , heaviside(x) , mystep(x));
Resulting in:
x^2*(heaviside(x) - abs(heaviside(x) - 1/2) + 1/2)
Which does not look nice but implements the intended behaviour.

I found the answer. I have to define a new function in which mystep = round(heaviside(x));
end

Related

fzero() Matlab function for complicated functions

Having such a function:
y=1.2*sin(x)+2*log(x+2)-5; I am looking for zeros of that function using fzero() functon- just for testing, I indicate other methods.
I received error and I am looking for the solution of that. fzero() is for nonlinear functions but for complex ones...? Doyou know similar method to fzero()?
The function in the example has a pole, but you can treat this case by looking at it's real part, get the zero and check it to see the imaginary part is zero:
syms x y yr
yr= #(x) real(1.2*sin(x)+2*log(x+2)-5);
fr=fzero(yr,0);
fr =
6.8458
y= #(x) (1.2*sin(x)+2*log(x+2)-5);
y(fr)
ans =
-8.8818e-16

Matlab: Meaning of #(t)(costFunction(t, X, y)) from Andrew Ng's Machine Learning class

I have the following code in MATLAB:
% Set options for fminunc
options = optimset('GradObj', 'on', 'MaxIter', 400);
% Run fminunc to obtain the optimal theta
% This function will return theta and the cost
[theta, cost] = ...
fminunc(#(t)(costFunction(t, X, y)), initial_theta, options);
My instructor has explained the minimising function like so:
To specify the actual function we are minimizing, we use a "short-hand"
for specifying functions, like #(t)(costFunction(t, X, y)). This
creates a function, with argument t, which calls your costFunction. This
allows us to wrap the costFunction for use with fminunc.
I really cannot understand what #(t)(costFunction(t, X, y) means. What are the both ts are doing? What kind of expression is that?
In Matlab, this is called an anonymous function.
Take the following line:
f = #(t)( 10*t );
Here, we are defining a function f, which takes one argument t, and returns 10*t. It can be used by
f(5) % returns 50
In your case, you are using fminunc which takes a function as its first argument, with one parameter to minimise over. This could be called using
X = 1; y = 1; % Defining variables which aren't passed into the costFunction
% but which must exist for the next line to pass them as anything!
f = #(t)(costFunction(t, X, y)); % Explicitly define costFunction as a function of t alone
[theta, cost] = fminunc(f, 0, options);
This can be shortened by not defining f first, and just calling
[theta, cost] = fminunc(#(t)(costFunction(t, X, y)), 0, options);
Further reading
As mentioned in the comments, here is a link to generally parameterising functions.
Specifically, here is a documentation link about anonymous functions.
Just adding to Wolfie's response. I was confused as well and asked a similar question here:
Understanding fminunc arguments and anonymous functions, function handlers
The approach here is one of 3. The problem the anonymous function (1 of the 3 approaches in the link below) solves is that the solver, fminunc only optimizes one argument in the function passed to it. The anonymous function #(t)(costFunction(t, X, y) is a new function that takes in only one argument, t, and later passes this value to costFunction. You will notice that in the video lecture what was entered was just #costFunction and this worked because costFunction only took one argument, theta.
https://www.mathworks.com/help/optim/ug/passing-extra-parameters.html
I also had the same question. All thanks to the the link provided by Wolfie to understand paramterized and anonymous functions, I was able to clarify my doubts. Perhaps, you must have already found your answer but am explaining once again, for people who might develop this query in the mere future.
Let's say we want to derive a polynomial, and find its minimum/maximum value. Our code is:
m = 5;
fun = #(x) x^2 + m; % function that takes one input: x, accepts 'm' as constant
x = derive(fun, 0); % fun passed as an argument
As per the above code, 'fun' is a handle that points to our anonymous function, f(x)=x^2 + m. It accepts only one input, i.e. x. The advantage of an anonymous function is, one doesn't need to create a separate program for it. For the constant, 'm', it can accept any values residing in the current workspace.
The above code can be shortened by:
m = 5;
x = derive(#(x) x^2 + m, 0); % passed the anonymous function directly as argument
Our target is to find the global optimal,so i think the function here is to get a bounch of local minimal by change the alpha and compare with each other to see which one is the best.
to achive this you initiate the fminuc with value initial_theta
fminuc set t=initial_theta then compute CostFunction(t,X,y) which is equal to` CostFunction(initial_theta,X,y).you will get the Cost and also the gradient.
fminuc will compute a new_theta with the gradient and a alpha, then set t=new_theta and compute the Cost and gradient again.
it will loop like this until it find the local optimal.
Then it change the length of alpha and repeat above to get another optimal. At the end it will compare the optimals and return with the best one.

Double integral with variable limits over implicit function in MATLAB

I'm experiencing the problem because of variable limit and implicit funtion being together.
So let's simplify it to this:
s(y)=y - our "implicit" function
Int [Int(x*s(y)*dy, 1,x)*dx, 1, 2] - our double integral (which equals 9/8).
(So you can even separate in into 2 integral I_small= s(y)dy and I=I_small * x*dx)
All that I figured out:
1) I tried using quad2d (so there is no ploblem with variable limit) - but I can't put the root of implicit function in it . So it wotks for non-implicit function:
function main
quad2d(#myfun,1,2,1,#(x)x)
end
function value=myfun(x,y)
value=x.*y;
end
But for implicit I've tried that - and it doesn't work. I know there is something wrong with this code - matlab doesn't understand that argument "y" in function name and "y" in the function itself are the same. But don't know how to fix it.
function main
quad2d(#myfun,1,2,1,#(x)x)
end
function value=myfun(x,y)
f=#(s,y)s-y;
value=x.*fzero(#(s)f(y,s), 0.5);
end
2) This code solves the opposite I = s(x).*y and I can't understand how to switch x to y because fzero doesnt work if I place y in it instead of x(j)
function main
quad(#myfun, 0,1)
end
function z=myfun(x)
z=zeros(size(x));
f=#(x,s) s-x;
for j=1:length(x);
s(j)=fzero(#(s)f(x(j),s), 0.5);
h=#(y) (s(j).*y);
z(j)=quad(h,1,x(j));
end
end
3) I also tried the nested quads, but it only works with constant limits. Can't fiqure it out how instead of Upperlimit should I place #(x)x.
function main
quad(#(y)y.*first_int(2),1,2)
end
function value=first_int(UpperLimit)
value=quad(#(x)yfunction(x,1),1,UpperLimit);
end
function value=yfunction(x,l)
syms y;
f=#(x,y) l.*x-y;
for k=1:length(x)
value(k)=fzero(#(y)f(x(k),y), 0.5);
end
Could you guys help with that?
The command quad2d (as its modern and better counterpart integral2) requires that the function to be integrated accept matrices as inputs.
The function Z=FUN(X,Y) must accept 2D matrices X and Y of the same size and return a matrix Z of corresponding values.
On the other hand, fzero only solves one equation, not a whole bunch of them at once. So, in order for your implicit function to accept matrix inputs, it needs to be written with a loop:
function value = myfun(x,y)
f=#(s,y)s-y;
value = zeros(size(x));
for i=1:size(x,1)
for j=1:size(x,2)
value(i,j) = x(i,j)*fzero(#(s) f(y(i,j),s), 0.5);
end
end
end
Then quad2d(#myfun,1,2,1,#(x)x) or integral2(#myfun,1,2,1,#(x)x) will work.

Evaluate Matlab symbolic function

I have a problem with symbolic functions. I am creating function of my own whose first argument is a string. Then I am converting that string to symbolic function:
f = syms(func)
Lets say my string is sin(x). So now I want to calculate it using subs.
a = subs(f, 1)
The result is sin(1) instead of number.
For 0 it works and calculates correctly. What should I do to get the actual result, not only sin(1) or sin(2), etc.?
You can use also use eval() to evaluate the function that you get by subs() function
f=sin(x);
a=eval(subs(f,1));
disp(a);
a =
0.8415
syms x
f = sin(x) ;
then if you want to assign a value to x , e.g. pi/2 you can do the following:
subs(f,x,pi/2)
ans =
1
You can evaluate functions efficiently by using matlabFunction.
syms s t
x =[ 2 - 5*t - 2*s, 9*s + 12*t - 5, 7*s + 2*t - 1];
x=matlabFunction(x);
then you can type x in the command window and make sure that the following appears:
x
x =
#(s,t)[s.*-2.0-t.*5.0+2.0,s.*9.0+t.*1.2e1-5.0,s.*7.0+t.*2.0-1.0]
you can see that your function is now defined by s and t. You can call this function by writing x(1,2) where s=1 and t=1. It should generate a value for you.
Here are some things to consider: I don't know which is more accurate between this method and subs. The precision of different methods can vary. I don't know which would run faster if you were trying to generate enormous matrices. If you are not doing serious research or coding for speed then these things probably do not matter.

How do I make a function from a symbolic expression in MATLAB?

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}