Matlab - how to build functions - matlab

Matlab has the function Legendre that returns to an integer m and real number r a vector of length m+1.
Now I want to define another function fun that gives me only the first component of this vector per fixed m, so I want to define a function fun(m,r) that gives me the first component of the vector legendre(m,x). The point is that fun(m,r) should also be a function, just like legendre. Does anybody know how to do this?

Define the function as follows:
function out = fun(n,x)
temp = legendre(n,x); %// store output of "legendre" in a temporary variable
out = temp(1); %// return only desired element
Of course, this should be placed in a file fun.m within Matlab's path.
Alternatively, if you are feeling hackish, you can use
getfield(legendre(n,x), {1})
to extract the first element of legendre(n,x) directly (without a temporary variable). This allows defining fun as an anonymous function as follows:
fun = #(n,x) getfield(legendre(n,x), {1});

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

How to create a function to calculate g(1,2) g(2,3) g(1,3) for equations like this g(1)+g(2)+g(1)*g(2)?

I'm trying to create Matlab code to calculate these following equations in Matlab
g(1,2)=g(1)+g(2)+g(1)g(2)
g(1,3)=g(1)+g(3)+g(1)g(3)
g(2,3)=g(2)+g(3)+g(2)g(3)
and values of g(1), g(2),g(3) are available.
Where should I start to write such Matlab code?
One problem here appears to be that you have functions of one and two variables, but you're calling them the same thing (g). Let's call the function of one variable g and the function of two variables (that you want to create) f. Assuming the function g already exists, you can create f using an anonymous function like so:
f = #(x1, x2) g(x1)+g(x2)+g(x1)*g(x2);
And calling it like this:
result = f(1, 2);
is equivalent to:
result = g(1)+g(2)+g(1)*g(2);

how to evaluate to multivariable function

Consider the function f(y1,y2,y3,y4,z1)=(-(z1^3)/(y3^2))(3(y2-y1+y3^(-1)-z1/10)^2+(1/5)(y2-y1+y3^(-1)-(z1)/10))-y4 with 5 variables. When I put f(1,1,1,1,1) I find the answer but when I write f(v) in which v=(1,1,1,1,1) matlab does not work. How can I do that (by the second way)?
You could write a wrapper function, that will take a vector as input argument and 'unpacks' this vector before calling your function.
f(y1,y2,y3,y4,z1) = (-(z1^3)/ ...; % your function
fv(v) = f(v(1),v(2),v(3),v(4),v(5));
Or alternatively, make f refer to elements in the input vector by using the appropriate indices:
f(v) = (-(v(5)^3)/(v(3)^2)); ... % etc.

Create function with given number of input arguments

Here's the situation:
I need to create a function that takes a function handle fun which is of CONSTANT input-length (that is nargin(fun)>=0), does some transformation on the inputs and then calls fun.
Pseudo-Code:
function g = transformFun(fun)
n = nargin(fun);
g = #(v_1, ..., v_n) ...
% ^ NOT REAL MATLAB - THE MAIN PROBLEM
fun(someCalculationsWithSameSizeOfOutput(v_1,...v_n){:});
% CAN BE ACHIEVED WITH TEMPORARY CELL IN HELPER FUNCTION ^
end
Now the problem: the output function's handle (g = transformFun(concreteFun)) is then passed to other code that relies on the fact that the function is of constant length (assumes nargin(g)>=0), thus a variable-input-length function is unacceptable (the "easy" solution).
This transformation is called with many functions with every possible number of arguments (n is unbounded), so covering a finite number of possibilities is also not possible.
Is there a (simple?) way to achieve that?
[I've searched the internet for a few hours and could only come up with a nasty hack involving the deprecated inline function, which I couldn't make work; maybe I have the wrong terminology].
So typically you could use varargin to handle this sort of thing, but since you need nargin(g) to return the actual number of inputs it's a little trickier.
You could use str2func to create the anonymous function as a string and then convert it to a function handle.
% Create a list or arguments: x1, x2, x3, x4, ...
args = sprintf('x%d,', 1:nargin(func));
args(end) = '';
% Place these arguments into a string which indicates the function call
str = sprintf('#(%s)fun(someCalculationsWithSameSizeOfOutput(%s))', args, args);
% Now create an anonymous function from this string
g = str2func(str);
Based on the attrocity above, it may be worth considering an alternative way of dealing with your function handles.

MATLAB Function (Solving an Error)

I have one file with the following code:
function fx=ff(x)
fx=x;
I have another file with the following code:
function g = LaplaceTransform(s,N)
g = ff(x)*exp(-s*x);
a=0;
b=1;
If=0;
h=(b-a)/N;
If=If+g(a)*h/2+g(b)*h/2;
for i=1:(N-1)
If=If+g(a+h*i)*h;
end;
If
Whenever I run the second file, I get the following error:
Undefined function or variable 'x'.
What I am trying to do is integrate the function g between 0 and 1 using trapezoidal approximations. However, I am unsure how to deal with x and that is clearly causing problems as can be seen with the error.
Any help would be great. Thanks.
Looks like what you're trying to do is create a function in the variable g. That is, you want the first line to mean,
"Let g(x) be a function that is calculated like this: ff(x)*exp(-s*x)",
rather than
"calculate the value of ff(x)*exp(-s*x) and put the result in g".
Solution
You can create a subfunction for this
function result = g(x)
result = ff(x) * exp(-s * x);
end
Or you can create an anonymous function
g = #(x) ff(x) * exp(-s * x);
Then you can use g(a), g(b), etc to calculate what you want.
You can also use the TRAPZ function to perform trapezoidal numerical integration. Here is an example:
%# parameters
a = 0; b = 1;
N = 100; s = 1;
f = #(x) x;
%# integration
X = linspace(a,b,N);
Y = f(X).*exp(-s*X);
If = trapz(X,Y) %# value returned: 0.26423
%# plot
area(X,Y, 'FaceColor',[.5 .8 .9], 'EdgeColor','b', 'LineWidth',2)
grid on, set(gca, 'Layer','top', 'XLim',[a-0.5 b+0.5])
title('$\int_0^1 f(x) e^{-sx} \,dx$', 'Interpreter','latex', 'FontSize',14)
The error message here is about as self-explanatory as it gets. You aren't defining a variable called x, so when you reference it on the first line of your function, MATLAB doesn't know what to use. You need to either define it in the function before referencing it, pass it into the function, or define it somewhere further up the stack so that it will be accessible when you call LaplaceTransform.
Since you're trying to numerically integrate with respect to x, I'm guessing you want x to take on values evenly spaced on your domain [0,1]. You could accomplish this using e.g.
x = linspace(a,b,N);
EDIT: There are a couple of other problems here: first, when you define g, you need to use .* instead of * to multiply the elements in the arrays (by default MATLAB interprets multiplication as matrix multiplication). Second, your calls g(a) and g(b) are treating g as a function instead of as an array of function values. This is something that takes some getting used to in MATLAB; instead of g(a), you really want the first element of the vector g, which is given by g(1). Similarly, instead of g(b), you want the last element of g, which is given by g(length(g)) or g(end). If this doesn't make sense, I'd suggest looking at a basic MATLAB tutorial to get a handle on how vectors and functions are used.