MATLAB's legendre function returns an array - matlab

I am working with an equation from a book and it works when I used Mathematica to solve it. It essentially contains the integral of certain orders of Legendre polynomials. E.g. P_1(x), P_2(x), P_3(x).
When I use Mathematica for a particular case e.g.
LegendreP[3, 0.5]
I get
-0.4375
which allows me to continue with my evaluation. But in MATLAB I get:
>> legendre(3,0.5)
ans =
-0.4375
-0.3248
5.6250
-9.7428
The first returned value is always correct but then it spits out... I think the other coefficients? So what I would like to do is tell MATLAB just to return the first value. Is there a way to do this without assigning it to its own variable afterwards? Eg. something like
legendre(3,0.5)(1)
Obviously wont work because it doesn't exist in memory yet. Am I even going about this the right way?
Thanks

If it bothers you, just put legendre into a new function legendre1, so you're using the library function, but with your desired functionality.
function [ P ] = legendre1( n,X )
P = legendre(n,X);
P = P(1);
end
or implement a custom range:
function [ P ] = legendre1( n,X,range )
P = legendre(n,X);
P = P(range);
end
so legendre1( 3,0.5,1 ) will return:
P =
-0.4375
and legendre1( 3,0.5,1:2 )
P =
-0.4375
-0.3248

Related

How to create a function that takes a matrix as an input?

I am new to MatLab.
Write a function that takes as input a matrix D ∈ R^(N×2), D_i = (x_i,y_i), and the period ω and returns a plot showing a fit of the data without noise.
I need help with creating the function that takes the input as a matrix and period ω. Here is what I have so far. Am I on the right track?
function F = fftfuntion(D, omega)
check = 0;
x = D(:,1);
y = D(;,2);
You are on track but there are 3 problems:
First: you are using p variable inside your function which is not defined there. If it is defined in your main code you have to insert it to this function by adding an input to your function as p and when the function is called you have to put p there. Your other solution is to set p as a global variable which is not recommended.
function F = fftfuntion(D, omega,p)
Second: you have said that you need omega as an input and you are changing it with omega = 2*pi which is not right.
Finally I don't see any output which I think that's because you are not still done with the function.
Good luck

Summation of N function handles in MATLAB

I have N functions in MATLAB and I can define them using strcat, num2str and eval in a for loop. So without defining by hand I am able to define N functions. Let N=4 and let them be given as follows:
f1=#(x) a1*x+1;
f2=#(x) a2*x+1;
f3=#(x) a3*x+1;
f4=#(x) a4*x+1;
Now I add these four functions and I can do this by hand as follows:
f=#(x)(f1(x)+f2(x)+f3(x)+f4(x));
Here I can do it by hand because I know that N=4. However, in general I never know how many functions I will have. For all cases I cannot write a new function.
Is there any way to do this automatically? I mean if I give N=6 I am expecting to see MATLAB giving me this:
f=#(x)(f1(x)+f2(x)+f3(x)+f4(x)+f5(x)+f6(x));
Whenever I give N=2 then I must have the function f, defined as follows:
f=#(x)(f1(x)+f2(x));
How can we do this?
First of all, you should read this answer that gives a series of reasons to avoid the use of eval. There are very few occasions where eval is necessary, in all other cases it just complicates things. In this case, you use to dynamically generate variable names, which is considered a very bad practice. As detailed in the linked answer and in further writings linked in that answer, dynamic variable names make the code harder to read, harder to maintain, and slower to execute in MATLAB.
So, instead of defining functions f1, f2, f3, ... fN, what you do is define functions f{1}, f{2}, f{3}, ... f{N}. That is, f is a cell array where each element is an anonymous function (or any other function handle).
For example, instead of
f1=#(x) a1*x+1;
f2=#(x) a2*x+1;
f3=#(x) a3*x+1;
f4=#(x) a4*x+1;
you do
N = 4;
a = [4.5, 3.4, 7.1, 2.1];
f = cell(N,1);
for ii=1:N
f{ii} = #(x) a(ii) * x + 1;
end
With these changes, we can easily answer the question. We can now write a function that outputs the sum of the functions in f:
function y = sum_of_functions(f,x)
y = 0;
for ii=1:numel(f)
y = y + f{ii}(x);
end
end
You can put this in a file called sum_of_functions.m, or you can put it at the end of your function file or script file, it doesn't matter. Now, in your code, when you want to evaluate y = f1(x) + f2(x) + f3(x)..., what you write is y = sum_of_functions(f,x).

matlab inline function with argument conditions

folks,
I am wondering if it is possible to write the following function of r as an inline function in matlab. I tried to include the condition as a separate factor such as *(r>a) and I got NaN due to the division of 1/r^3 when r is 0.
I fould a simple way out. It's basically what Shai and Jigg suggested, i.e. using an extra multiplicative factor of (r>a).
To get rid of NaN, we just need to add eps to the denominator of 1/r3, i.e.
1/(r+eps)^3 *(r>a)
First, you haven't stated what should actually happen if r = 0. Mathematically the term gets infinity. I assumed you rather want to set it to zero. And what should happen for r = a? Just another ill-defined case, are you sure your formula is correct?
If you have the Statistics Toolbox you can use nansum. If not, I'd say there is no way around to write your own function similar to nansum, which can't be done inline.
r = -5:1:5;
a = 1;
R = 42; %// rest of your function
%// not working, or removing of nan afterwards required
X = #( r ) (r>=a).*(a./r).^3*R;
%// inline solution with statistics toolbox
Y = #( r ) arrayfun(#(x) nansum( (x>=a)*(a/x)^3*R ), r);
output = [X(r)' Y(r)']
nansum is not vectorized, if you still want to use it for vectors wrap it into arrayfun.
The code of nansum does exactly what was suggested in the comments (output(isnan(output))=0), I'm probably not allowed to copy&paste it here. It filters out all NaN and then sums the input. Use open nansum to have insight.
As pointed out by Jigg, similar functions like nanmean would do the trick as well.
You can try
chi = 1; %// arbitrary value
a = 1; %// arbitrary value
theta = pi/3; %// arbitrary value
nu = #( r ) (r>a).*( (chi/3).*((a.^3)./(r.^3)).*(3*cos(theta).^2 -1);

Matlab while looping; a function within a function

How do i loop a function inside another function until both sides equal each other ?
for example
after I find this "f"
f = (1/(-1.8*log(((epsilon/D)/3.7)^2 + 6.9/Re)))^2;
I want to use that value of f and input it here
f = (1/ -2.0*log((epsilon/D) + (2.51/Re*sqrt(***f***))))^2
the program is supposed to loop until both sides equal each other or are relatively close. the acceptable accuracy or error is 0.00001.
and how do I display that value of f that gives mme wha
It seems to me you are trying to solve an expression
f = somefun(f);
where the initial value for f is given by
f = (1/(-1.8*log(((epsilon/D)/3.7)^2 + 6.9/Re)))^2
Your best bet (if it's available to you) is to use Matlab's optimization toolbox, where you set the function to be minimized to
f - somefun(f)
and where you can set the tolerance using optimset('TolFun', 1e-5);
If you don't have the toolbox, then drN's suggestion in the comments of using Newton's method is probably as good as any -and you will learn more from doing it yourself.
I'm assuming that's fix point iteration you are attempting to use there, with your first code line being a starting estimate and your second code line being the actual fixed point iteration.
In this case you need to simply repeat that second statement while testing the difference between successive iterations. Something like this for example.
f = 1;
df = 1;
while abs(df) > 0.0001
fnew = log(20/f);
df = fnew - f;
f = fnew;
end;
BTW. The above is a simple example of fixed point iteration to solve f*exp(f)=20, [or equivalently f = ln(20/f)]. Apply the same logic to your particular equation for "f", but beware that not all equations are amenable to fixed point iteration.

Passing argument to inner function Matlab

So I'm trying to write a function for a triple integral which depends ultimately on variable q which is a final limit of integration, and also a variable b which helps parameterize the function. However, this code isn't working and I'm not entirely sure what to do. I think it probably involves doing something to pass down the value of b to the nested functions, but I'm pretty new at matlab, any help is appreciated.
function [r] = test1(q,u)
b = u;
r = quad(#(k)Inner(k),-0.5.*(1-b)-b-1,q);
function [w] = Inner(k)
w = zeros(1);
for i = 1 : length(k);
w(i) = quad(#(n)InnerIntegral(n,b).*unifpdf(k(i)-n,-1,1),0,k(i)-1,k(i)+1);
end;
function [y] = InnerIntegral(n)
y = zeros(1);
for i = 1 : length(n);
y(i) = quad(#(m)unifpdf(n(i)-m, -b, b).*unifpdf(m,-0.5.*b,0.5.*b), n(i)-b,n(i)+b);
end;
end
end
end
Look at the little orange tick marks on the right side of the editor. In my copy, hovering over one says "Outer loop index 'i' is set inside a child function."
I don't know what the inputs or expected outputs of this function should be, but you should try to avoid confusing MATLAB. It has weird scoping rules. Use a different variable in the second nested function, perhaps j instead of i.