How should I rewrite this code to not use feval? - numerical-methods

I recently finished a homework set in my Applied Numerical Methods class and did alright on it. However, my professor made a note to say I shouldn't use the feval() function because it's outdated.
I'm just wondering what I should use instead.
Here is the code in question
%% function file
function E=euler(f,a,b,ya,h)
t=a:h:b;
y(1)=ya;
for i=1:length(t)-1
y(i+1) = y(i) + h*(feval(f,t(i),y(i)));
end
t = t';
y = y';
E=t;
plot(t,y)
xlabel('t')
ylabel('y')
end
%% script file
f = #(y,t) (1-20*t*y)/(t^2); %solved for dy/dt
x = 2:0.0001:10;
exact = 1./(19.*x) - 524288./(19.*x.^20);
figure(1)
plot(exact);
a = 2;
b = 10;
ya = 1;
h = 0.01;
figure(2)
y1=euler(f, a, b, ya, h);
h = 0.001;
figure(3)
y2=euler(f, a, b, ya, h);
h = 0.0001;
figure(4)
y3=euler(f, a, b, ya, h);
How could I write this code to still properly evaluate the Euler function without using the feval function.

For example, you can see that
[V,D] = feval('eig',A)
[V,D] = eig(A)
Are equivalent.

Related

how to create multivariate function handle in matlab in this case?

I would like to create a multivariate functional handle which the number of variables is changeable according to the input.
First, create n symbolic variables, and note that n can be changed according to your input.
n=3;
syms theta [1 n];
Now I create a function g. Via For loop, create the summation of g on all theta. As seen in the code, f is a symbolic expression.
g = #(x)(x^2);
f = 0;
for i = 1:n
f = f + g(sym(sprintfc('theta%d',i)))
end
Now I want to create a functional handle F according to f.
One potential way to do this F = #(theta1,theta2,theta3)(f). However, since n is user-specified, changeable variable, this approach is not doable.
Could someone give my hint? Many thanks!
Is this what you are looking for?
g = #(x)x.^2
fn = #(varargin) sum( cellfun(g,varargin) )
Now we have an anonymous function with a variable number of inputs. Example use below
fn(1) % = 1
fn(1,5,3) % = 35 = (1^2+5^2+3^2)
fn(1,2,3,4,5,6) % = 91 = (1^2 + 2^2 + 3^2 + 4^2 + 5^2 + 6^2)

Duplicating functions in Julia

I need to overwrite a function based on its previous definition, and this leads to a stackoverflow error.
I have tried with deepcopy(f), but it just returns a reference to f, so this doesn't work.
What I need to be able to do over and over is:
Old(x) = pdf(Uniform(),x)
New(x) = updating_function(Old, Y1)
Old(x) = deepcopy(New(x))
New(x) = updating_function(Old, Y2)
[...]
EDIT:
My overall goal is to have a function that takes a prior distribution and spits out a posterior with an unusual signal structure due to my application.
A simple running example of this would be
Old_pdf(x)= pdf(Uniform(),x)
Old_mean=0.5
function BU(d,low)
value, tol = quadgk(Old_pdf, Old_λ, 1)
truncated(λ)=d(λ)/value
end
Newpdf=BU(Old_pdf,Old_mean)
Old_mean, tol= quadgk(x -> Newpdf(x)*x, Old_mean, 1)
Old_pdf=BU(Old_pdf,Old_mean)
I know that this example could be addressed with functions from the Distributions package. It's not the case for my application.
I have found this question and read the documentation of the IRTools package, but I am unable to make this work. In particular when I try
Old(x) = pdf(Uniform(),x)
New(x) = updating_function(Old, Y1)
const Old_ir= IRTools.Inner.code_ir(New, Tuple{Int})
Old(x) = IRTools.func(Old_ir)
I obtain an object that doesn't behave like a function, hence generates methods error in the rest of the code. I made several attempts at this, and it is entirely possible that I am missing something trivial.
Y1 = 5.0
Y2 = 7.0
updating_function(f1,c) = x -> 2.0 * f1(x) + c
Old = x->sqrt(x)
New = updating_function(Old, Y1)
Old = New
New = updating_function(Old, Y2)
I think you just need anonymous functions:
function BU(f, λ, y)
# I guess here you would use the observations `y` in some way?
z, _ = quadgk(f, λ, 1)
return λ -> f(λ) / z
end
mean(f, λ) = quadgk(x -> f(x) * x, λ, 1)[1]
original_pdf(x) = pdf(Uniform(), x)
f = original_pdf
λ = 0.5
for y in Y
f = BU(f, λ, y)
λ = mean(f, λ)
end
Now I tried very hard, and I think I understand what you're doing, but the example you gave wasn't very clear. Consider this conceptual.
Such things make nice folds, by the way.

Writing simple equations in Octave

Imagine I want to define a function in Octave z(var1, var2) = a(var1) + b(var1) + c(var2) + d(var2) + const. Prior to this definition, I would like to define all the neccessary functions, something like: a(var1) = var1^2 + const, b(var1) = cos(var1), c(var) = sqrt(var2 - const) etc. Later in time, I add all those functions and form the final one, z function. Afterwards, I'd like to get partial derivatives of the function z in respect to var1 and var2.
So far, my only concern is defining the functions above to work as i imagined; is it possible and how ?
You can use function handles and anonymous functions:
a = #(x) x^2 + c1;
b = #cos;
c = #(x) sqrt(x - c2);
d = #exp;
b and d are handles to existing functions. You can call them as regular functions using b(...) or d(...). a and c are anonymous functions. They provide the argument list and definition of the handle right there in the assignment, somewhat like Python's lambdas. You could do something like b = #(x) cos(x), but there is really no point since there are no additional operations necessary.
Now you can do
z = #(x, y) a(x) + b(x) + c(y) + d(y) + c3;
The alternative is to write separate m-files for each function, which I am assuming you would like to avoid.
Using the function, for example to take partial derivatives, is now fairly straightforward. Function handles are called just like any other builtin or m-file-defined function:
(z(x + delta, y) - z(x - delta, y)) / (2 * delta)
Update
Just for fun, I ran the following script (using Octave 3.4.3 on Red Hat 6.5):
octave:1> c1 = -100;
octave:2> c2 = -10;
octave:3> c3 = 42;
octave:4> a = #(x) x^2 + c1;
octave:5> b = #cos;
octave:6> c = #(x) sqrt(x - c2);
octave:7> d = #exp;
octave:8> z = #(x, y) a(x) + b(x) + c(y) + d(y) + c3;
octave:9> [X, Y] = meshgrid([-10:0.1:10], [-10:0.1:10]);
octave:10> surf(X, Y, z(X, Y));
The result is not especially interesting, but it does demonstrate the effectiveness of this technique:
Here is an IDEOne link to play with.

Is it possible to know the name of the variable that provides the value in a function call in Octave?

Say that myFunction has been invoked from somewhere like this
...
myFunction (b);
...
Now, in the definition of myFunction, can I obtain the name of the variable in the call?
function myFunction (a)
...
inputVble = whoscalling; % this will result in "b"
...
May be it can be done if b is a global variable?
Note: this is not like in a couple other questions, where you want to know the name of the input argument, i.e. a.
function ret = doit (a, b)
inputname (1)
inputname (2)
ret = a + b;
endfunction
x = 4;
y = 5;
doit (x, y)
returns
ans = x
ans = y
ans = 9
But I want to mention that in my opinion, making a function somewhat dependent on the function names is bad style and shouldn't be done even if it's possible.
EDIT: I think the main reasonable use for inputname is inside a display routine for #classes. For example http://hg.savannah.gnu.org/hgweb/octave/file/51a1d1164449/examples/code/%40polynomial/display.m
function display (p)
...
fprintf ("%s =", inputname (1));
Or inside celldisp:
octave:2> a = {"huhu", pi}
a =
{
[1,1] = huhu
[1,2] = 3.1416
}
octave:3> celldisp (a)
a{1} =
huhu
a{2} =
3.1416

Octave integrating

I have some problems with integrating in Octave.
I have the following code:
a=3;
function y = f (x)
y = x*x*a;
endfunction
[v,ier,nfun,err]=quad("f",0,3);
That 'a' in function is giving me troubles.
Octave says that 'a' is undefined. So, if I instead of 'a' put number 3 in function y everything works just fine. However, I want to have 'a' in function so I can change it's value.. How do I do that?
Thanks
You could use a function closure, which will encapsulate the a.
function f = makefun (a)
f = #(x) x * x * a;
endfunction
f = makefun(3)
[v, ier, nfun, err] = quad(f, 0, 3);
There are two main options.
Option 1 is, as voithos notes, make 'a' an input to the function.
Option 2 is to define 'a' to be a global variable.
global a=3;
function y = f (x)
global a
y = x*x*a;
endfunction
[v,ier,nfun,err]=quad("f",0,3);
This will cause 'a' to be the same value inside and outside the function.
Your function is actually dependent on two values, x and a, therefor:
f=#(x,a) x*x*a
[V, IER, NFUN, ERR] = quad (#(x) f(x,3), A, B, TOL, SING)
I used inline functions as i think it is easier to understand.