MATLAB Symprod? Need to return a function that a product series should return - matlab

So Im trying to calculate how to compute Newtons Forward Difference method for a unit in uni, and its the last question on this group assignment I need to complete.
It's hard to explain really what it does without writing a couple paragraphs, but it generally interpolates polynomial functions, and returns a function, in other words you provide some X and Y coordinates you know this function should pass through, and it will return some function that really closely approximates the actual function, and does pass through those points. So really useful stuff.
Anyway...
I have a massive function that this all gets plugged in to, but what Im having trouble with is returning a function from a product series.
The series is something like...
s(s-1)(s-2)...(s-n+1) %Not coded obviously
Where,
s = #(x) (x - X(1))/h;
So s is a function of x, and Im trying to get the function of that series in terms of x. Any help would be highly appreciated.
My attempt is this:
func = #(x) Y(1) + symprod(s*(s-n+1)) ./ factorial(n);
Includes a few extra things I havn't mentioned, but it still involves my attempt at getting a function in terms of s for the product series...
n is just an integer, known value.
Even after using isolate function as suggested below, still no result. Not really sure what to do, someone hellpp

Managed to figure this out, so I never actually ended up getting the above method to work, wherein I was trying to get a function from a bunch of variables, and an infinite product series, I ended up just using a for loop to simulate the product infinite series, got that value, and then when I wanted a function I simply wrote f = #(x) value_from_function(x).
For an example of some working code, I uploaded it on my GitHub...
So, in that example I would do
f = #(x) interpolating_polynomial(X, Y, x);

Related

Declaring a functional recursive sequence in Matlab

I'd like to declare first of all, that I'm a mathematician. This might be a stupid stupid question; but I've gone through all the matlab tutorials--they've gotten me nowhere. I imagine I could code this in C (it'd be exhausting); but I need matlab for this particular function. And I don't get exactly how to do it.
Here is the pasted Matlab code of where I'm running into trouble:
function y = TAU(z,n)
y=0;
for i =[1,n]
y(z) = log(beta(z+1,i) + y(z+1)) - beta(z,i);
end
end
(beta is an arbitrary "float" to "float" function with an index i.)
I'm having trouble declaring y as a function, in which we call the function at a different argument. I want to define y_n(z) with something something y_{n-1}(z+1). This is all done in a recursive process to create the function. I really feel like I'm missing something stupid.
As a default function it assigns y to be an array (or whatever you call the default index assignment). But I don't want an array. I want y to be assigned as a "function" class (i.e. takes "float" to "float"). And then I'm defining a sequence of y_n : "float" to "float". So that z to z+1 is a map on "float" to "float".
I don't know if I'm asking too much of matlab...
Help a poor mathematician who hasn't coded since the glory days of X-box mods.
...Please don't tell me I have to go back to Pari-GP/C drawing boards over something so stupid.
Please help!
EDIT: At rahnema1 & mimocha's request, I'll describe the math, and of what I am trying to do with my program. I can't see how to implement latex in here. So I'll write the latex code in a generator and upload a picture. I'm not so sure if there even is a work around to what I want to do.
As to the expected output. We'd want,
beta(z+1,i) + TAU(z+1,i) = exp(beta(z,i) + TAU(z,i+1))
And we want to grow i to a fixed value n. Again, I haven't programmed in forever, so I apologize if I'm speaking a little nonsensically.
EDIT2:
So, as #rahnema1 suggests; I should produce a reproducible example. In order to do this, I'll write the code for my beta function. It's surprisingly simple. This is for the case where the "multiplier" variable is set to log(2); but you don't need to worry about any of that.
function f = beta(z,n)
f=0;
for i = 0:n-1
f = exp(f)/(1+exp(log(2)*(n-i-z)));
end
end
This will work fine for z a float no greater than 4. Once you make z larger it'll start to overflow. So for example, if you put in,
beta(2,100)
1.4242
beta(3,100)
3.3235
beta(3,100) - exp(beta(2,100))/(1/4+1)
0
The significance of the 100, is simply how many iterations we perform; it converges fast so even setting this to 15 or so will still produce the same numerical accuracy. Now, the expected output I want for TAU is pretty straight forward,
TAU(z,1) = log(beta(z+1,1)) - beta(z,1)
TAU(z,2) = log(beta(z+1,2) + TAU(z+1,1)) - beta(z,2)
TAU(z,3) = log(beta(z+1,3) + TAU(z+1,2)) - beta(z,3)
...
TAU(z,n) = log(beta(z+1,n) + TAU(z+1,n-1)) -beta(z,n)
I hope this helps. I feel like there should be an easy way to program this sequence, and I must be missing something obvious; but maybe it's just not possible in Matlab.
At mimocha's suggestion, I'll look into tail-end recursion. I hope to god I don't have to go back to Pari-gp; but it looks like I may have to. Not looking forward to doing a deep dive on that language, lol.
Thanks, again!
Is this what you are looking for?
function out = tau(z,n)
% Ends recursion when n == 1
if n == 1
out = log(beta(z+1,1)) - beta(z,1);
return
end
out = log(beta(z+1,n) + tau(z+1,n-1)) - beta(z,n);
end
function f = beta(z,n)
f = 0;
for i = 0:n-1
f = exp(f) / (1 + exp(log(2)*(n-i-z)));
end
end
This is basically your code from the most recent edit, but I've added a simple catch in the tau function. I tried running your code and noticed that n gets decremented infinitely (no exit condition).
With the modification, the code runs successfully on my laptop for smaller integer values of n, where 1e5 > n >= 1; and for floating values of z, real and complex. So the code will unfortunately break for floating values of n, since I don't know what values to return for, say, tau(1,0) or tau(1,0.9). This should easily be fixable if you know the math though.
However, many of the values I get are NaNs or Infs. So I'm not sure if your original problem was Out of memory error (infinite recursion), or values blowing up to infinity / NaN (numerical stability issue).
Here is a quick 100x100 grid calculation I made with this code.
Then I tested on negative values of z, and found the imaginary part of the output to looks kinda cool.
Not to mention I'm slightly geeking out over the fact that pi is showing up in the imaginary part as well :)
tau(-0.3,2) == -1.45179335740446147085 +3.14159265358979311600i

Relate outputs of parent function to input of nested function

I am going to try and explain myself simply in the hopes of getting a simple answer.
Let's say I have a function 'calculate' that takes the inputs [t,k,r,x] and outputs [A,B,C,D] as follows:
function [A,B,C,D] = calculate(t,k,r,x)
Now lets say I have another function that takes these outputs as the inputs, and spits out more, different outputs, eg.
function [M,N] = again(A,B,C,D)
How do I link [M,N] to say k and t? The overall aim is to minimise both M and N by optimising k and t, and I can guess that it has something to do with nested functions and passing parameters but I'm not sure how to start, and the start is all I want. Thanks
Take a look at the Matlab optimization toolbox. It provides functions for a multitude of optimization problems. Although I believe these functions only take one function as a parameter. Therefore for your case it would probably be best, if you do it like this if you can:
Write function calculate.m with parameters (t,k,r,x) and save it.
Write function again.m with parameters(t,k,r,x) and save it.
Function again calls function calculate with parameters (t,k,r,x) and then continues to determine (M,N) from the output of calculate.
in the Matlab toolbox optimization function, e.g.: fmincon(fun,x0,A,b), you then have to use again.m as the function you want to optimize (fun).
Hope that's good enough for a start.

How to get the zeros of the given equation using fzero in MATLAB?

I have the following function that I wish to solve using fzero:
f = lambda* exp(lambda^2)* erfc(lambda) - frac {C (T_m - T_i)}/{L_f*sqrt(pi)}
Here, C, T_m, T_i, and L_f are all input by the user.
On trying to solve using fzero, MATLAB gives the following error.
Undefined function or variable 'X'.
(where X are the variables stated above)
This error is understandable. But is there a way around it? How do I solve this?
This is answered to the best of my understanding after reading your question as it's not really clear what you are exactly trying and what you want exactly.
Posting the exact lines of code helps a big deal in understanding(as clean as possible, remove clutter). If then the output that matlab gives is added it becomes a whole lot easier to make sure we answer your question properly and it allows us to try it out. Usually it's a good idea to give some example values for data that is to be entered by the user anyway.
First of to make it a function it either needs a handle.
Or if you have it saved it as a matlab file you generally do not want other inputs in your m file then the variable.
So,
function [out]=yourfun(in)
constants=your values; %you can set a input or inputdlg to get a value from the user
out= something something, your lambda thingy probably; %this is the equation/function you're solving for
end
Now since that is not all that convenient I suggest the following
%declare or get your constants here, above the function makes it easier
syms lambda
f = lambda* exp(lambda^2)* erfc(lambda) - frac {C (T_m - T_i)}/{L_f*sqrt(pi)};
hf=matlabFunction(f); %this way matlab automatically converts it to a function handle, alternatively put #(lambda) in front
fzero(hf,x0)
Also this matlab page might help you as well ;)

In Matlab, is there a way to take in a formula as parameter input?

This might seem like a strange thing to do, which it probably is. In my main (or how you call it in matlab) I would like to have all the information needed for the program to run. A change of variables or formulas should only happen in my main.
For example I would like to change the number of iterations and the formula of the hypothese in my main and let other function use these, instead of declaring them within the function themselves and having to edit it all over the place. The problem I face is not knowing how to do this properly for hypothese_formula and wonder if there is a better way of doing this?
function prog1()
iterations = 1;
hypothese_formula = x^2;
doSomethingWithFormulaAndIterations(hypothese_formula, iterations);
end
Practical: I would to do linear regression with a hypothesis of the formula and specific starting values of theta and don't want them to be hidden within a function. I don't know how to declare global formula's.
You can use anonymous functions.
function prog1()
iterations = 1;
hypothese_formula = #(x) x.^2
doSomethingWithFormulaAndIterations(hypothese_formula, iterations);
end

MATLAB Using fzero - returns error

I'm trying to use the MATLAB function fzero properly but my program keeps returning an error message. This is my code (made up of two m-files):
friction_zero.m
function fric_zero = friction_zero(reynolds)
fric_zero = 0.25*power(log10(5.74/(power(reynolds,0.9))),-2);
flow.m
function f = flow(fric)
f = 1/(sqrt(fric))-1.873*log10(reynolds*sqrt(fric))-233/((reynolds*sqrt(fric))^0.9)-0.2361;
f_initial = friction_zero(power(10,4));
z = fzero(#flow,f_initial)
The goal is to return z as the root for the equation specified by f when flow.m is run.
I believe I have the correct syntax as I have spent a couple of hours online looking at examples. What happens is that it returns the following error message:
"Undefined function or variable 'fric'."
(Of course it's undefined, it's the variable I'm trying to solve!)
Can someone point out to me what I've done wrong? Thanks
EDIT
Thanks to all who helped! You have assisted me to eventually figure out my problem.
I had to add another file. Here is a full summary of the completed code with output.
friction_zero.m
function fric_zero = friction_zero(re)
fric_zero = 0.25*power(log10(5.74/(power(re,0.9))),-2); %starting value for fric
flow.m
function z = flow(fric)
re = power(10,4);
z = 1/(sqrt(fric))-1.873*log10(re*sqrt(fric))-233/((re*sqrt(fric))^0.9)-0.2361;
flow2.m
f_initial = friction_zero(re); %arbitrary starting value (Reynolds)
x = #flow;
fric_root = fzero(x,f_initial)
This returns an output of:
fric_root = 0.0235
Which seems to be the correct answer (phew!)
I realised that (1) I didn't define reynolds (which is now just re) in the right place, and (2) I was trying to do too much and thus skipped out on the line x = #flow;, for some reason when I added the extra line in, MATLAB stopped complaining. Not sure why it wouldn't have just taken #flow straight into fzero().
Once again, thanks :)
You need to make sure that f is a function in your code. This is simply an expression with reynolds being a constant when it isn't defined. As such, wrap this as an anonymous function with fric as the input variable. Also, you need to make sure the output variable from your function is z, not f. Since you're solving for fric, you don't need to specify this as the input variable into flow. Also, you need to specify f as the input into fzero, not flow. flow is the name of your main function. In addition, reynolds in flow is not defined, so I'm going to assume that it's the same as what you specified to friction_zero. With these edits, try doing this:
function z = flow()
reynolds = power(10,4);
f = #(fric) 1/(sqrt(fric))-1.873*log10(reynolds*sqrt(fric))-233/((reynolds*sqrt(fric))^0.9)-0.2361;
f_initial = friction_zero(reynolds);
z = fzero(#f, f_initial); %// You're solving for `f`, not flow. flow is your function name
The reason that you have a problem is because flow is called without argument I think. You should read a little more about matlab functions. By the way, reynolds is not defined either.
I am afraid I cannot help you completely since I have not been doing fluid mechanics. However, I can tell you about functions.
A matlab function definition looks something like this:
function x0 = f(xGuess)
a = 2;
fcn =#(t) a*t.^3+t; % t must not be an input to f.
disp(fcn);
a = 3;
disp(fcn);
x0 = fsolve(fcn1,xGuess); % x0 is calculated here
The function can then ne called as myX0 = f(myGuess). When you define a matlab function with arguments and return values, you must tell matlab what to do with them. Matlab cannot guess that. In this function you tell matlab to use xGuess as an initial guess to fsolve, when solving the anonymous function fcn. Notice also that matlab does not assume that an undefined variable is an independent variable. You need to tell matlab that now I want to create an anonymous function fcn which have an independent variable t.
Observation 1: I use .^. This is since the function will take an argument an evaluate it and this argument can also be a vector. In this particulat case I want pointwise evaluation. This is not really necessary when using fsolve but it is good practice if f is not a matrix equation, since "vectorization" is often used in matlab.
Observation 2: notice that even if a changes its value the function does not change. This is since matlab passes the value of a variable when defining a function and not the variable itself. A c programmer would say that a variable is passed by its value and not by a pointer. This means that fcn is really defined as fcn = #(x) 2*t.^3+t;. Using the variable a is just a conveniance (constants can may also be complicated to find, but when found they are just a value).
Armed with this knowledge, you should be able to tackle the problem in front of you. Also, the recursive call to flow in your function will eventuallt cause a crash. When you write a function that calls itself like this you must have a stopping criterium, something to tell the program when to stop. As it is now, flow will call ifself in the last row, like z = fzero(#flow,f_initial) for 500 times and then crash. Alos it is possible as well to define functions with zero inputs:
function plancksConstant = h()
plancksConstant = 6.62606957e−34;
Where the call h or h() will return Plancks constant.
Good luck!