How to use matrix entries in a double symsum? - matlab

I am trying to implement the following double summation in a function:
f(x,y)=\sum_{k=0}^{S}\sum_{l=0}^{S}{a_{kl}x^ky^l}.
Here is my first attempt:
function [ a ] = MyFun( S )
a=randi([0 9],S+1);
syms x y k l;
f(x,y)=symsum(symsum(a(k,l)*x^k*y^l,l,1,S+1),k,1,S+1);
f(1,2)
end
Actually, my code evaluates f in a loop later on, but that does not seem relevant here. Trying something like MyFun(3) results in an error:
Error using sym/subsindex (line 766) Invalid indexing or function
definition. When defining a function, ensure that the arguments are
symbolic variables and the body of the function is a SYM expression.
When indexing, the input must be numeric, logical, or ':'.
Error in MyFun (line 4)
f(x,y)=symsum(symsum(a(k,l)*x^(k-1)*y^(l-1),l,1,S+1),k,1,S+1);
Everything works fine if a(k,l)* is removed from the inner symsum, so I suspect that there is something wrong with the indices. Is it not possible to use the symbolical variables k and l as indices? If not, how can I solve this?

Indexing a matrix using a symbolic value does not seem to work. As an alternative you can use elementwise multiplication as follows:
function f = MyFun( S )
a=randi([0 9],S+1);
k = repmat((0:S)', 1, S+1);
l = repmat((0:S), S+1, 1);
syms x y;
f(x, y) = sum(sum(a .* x.^k .* y.^l));
end

Related

MATLAB Unable to Store Symbolic Function with Multiple Variables

I'm trying to take the definite integral from -1 to 1 of a function with respect to x. The function has variables a, b, c, d, and x, all of which I've defined as syms variables. I'm trying to keep a, b, c, d in my final integral because I'll later be differentiating with respect to each one for an optimization problem. Here's the current code that I have:
syms f(x);
syms a b c d;
f(x)= (exp(x)-a*(1/sqrt(2))-b*(sqrt(3/2)*x)-c((sqrt(45/8))*(x^2-(1/3)))+d((sqrt(175/8))*((x^3)-(3/5)*(x))))^2;
integral = int(f, x, [-1 1]);
disp(integral);
Similar code worked when I tried it using only variables x and y for a smaller function. However, when I try this code, I get:
Error using sym/subsindex (line 825) Invalid indexing or function
definition. Indexing must follow MATLAB indexing. Function arguments
must be symbolic variables, and function body must be sym expression.
Error in sym/subsref (line 870)
R_tilde = builtin('subsref',L_tilde,Idx);
Error in HW11 (line 4)
f(x)= (exp(x)-a*(1/sqrt(2))-b*(sqrt(3/2)x)-c((sqrt(45/8))(x^2-(1/3)))+d((sqrt(175/8))((x^3)-(3/5)(x))))^2;
I'm pretty new to symbolic functions and syms variables in MATLAB, why is MATLAB rejecting this code? The similar code that I tried that worked was:
syms f(x);
syms y;
f(x) = (x^2) + y;
integral = int(f, x, [0 3]);
disp(integral);
As mentioned in the comment by Adam, you probably forgot to add a multiplication operator * after the the c and d, so when you write c(...) and d(...) MATLAB treats these as indexing of an array but you cannot index arrays with symbolic variables or expressions. You need to change it to c*(...) and d*(...).
Replace:
f(x)= (exp(x)-a*(1/sqrt(2))-b*(sqrt(3/2)*x)-c((sqrt(45/8))*(x^2-(1/3)))+d((sqrt(175/8))*((x^3)-(3/5)*(x))))^2;
With:
f(x)= (exp(x)-a*(1/sqrt(2))-b*(sqrt(3/2)*x)-c*((sqrt(45/8))*(x^2-(1/3)))+d*((sqrt(175/8))*((x^3)-(3/5)*(x))))^2;

Double integral of objective function

I want to evaluate the double integral of my objective function (named myfunction, see below) using the build-in-function integral2.
I have tried to run this script;
f = #(r,theta) myfunction(r,theta);
integral2(f,0,2,0,2*pi);
where myfunction is the following function:
function fkt=myfunction(r,theta)
x=r.*cos(theta);
y=r.*sin(theta);
los(:,1)=x;
los(:,2)=y;
norm = (sum( sqrt( los(:,1).^2 + los(:,2).^2)));
fkt=norm*r;
end
I am making the integral in polar coordinates, that why fkt=norm*r.
Matlab gives me the following error message:
>> untitled2
Subscripted assignment dimension mismatch.
Error in myfunction (line 8)
los(:,1)=x;
I can't figure out, what the problem is.
There are two things that can be improved:
los is undefined
los(:,1) is a column while x is a row, so the assignment has to fail.
You can correct this by defining los and change your assignment. For instance:
los = NaN(numel(r), 2);
los(:,1) = x';
los(:,2) = y';
But, why do you need the variable los? Just remove it and the error will be gone:
function fkt=myfunction(r,theta)
x=r.*cos(theta);
y=r.*sin(theta);
norm = (sum( sqrt(x.^2 + y.^2)));
fkt=norm*r;
end
Best,
x is a matrix and you try to assign it to a column vector.

Bessel's integral implementation

I'm trying to implement this integral representation of Bessel function of the first kind of order n.
here is what I tried:
t = -pi:0.1:pi;
n = 1;
x = 0:5:20;
A(t) = exp(sqrt(-1)*(n*t-x*sin(t)));
B(t) = integral(A(t),-pi,pi);
plot(A(t),x)
the plot i'm trying to get is as shown in the wikipedia page.
it said:
Error using * Inner matrix dimensions must agree.
Error in besselfn (line 8) A(t) = exp(sqrt(-1)*(n*t-x*sin(t)));
so i tried putting x-5;
and the output was:
Subscript indices must either be real positive integers or logicals.
Error in besselfn (line 8) A(t) = exp(sqrt(-1)*(n*t-x*sin(t)));
How to get this correct? what am I missing?
To present an anonymous function in MATLAB you can use (NOT A(t)=...)
A = #(t) exp(sqrt(-1)*(n*t-x.*sin(t)));
with element-by-element operations (here I used .*).
Additional comments:
You can use 1i instead of sqrt(-1).
B(t) cannot be the function of the t argument, because t is the internal variable for integration.
There are two independent variables in plot(A(t),x). Thus you can display plot just if t and x have the same size. May be you meant something like this plot(x,A(x)) to display the function A(x) or plot(A(x),x) to display the inverse function of A(x).
Finally you code can be like this:
n = 1;
x = 0:.1:20;
A = #(x,t) exp(sqrt(-1)*(n*t-x.*sin(t)));
B = #(x) integral(#(t) A(x,t),-pi,pi);
for n_x=1:length(x)
B_x(n_x) = B(x(n_x));
end
plot(x,real(B_x))

Numerical integration of symbolic differentiation - MATLAB

The following is a MATLAB problem.
Suppose I define an function f(x,y).
I want to calculate the partial derivative of f with respect to y, evaluated at a specific value of y, e.g., y=6. Finally, I want to integrate this new function (which is only a function of x) over a range of x.
As an example, this is what I have tried
syms x y;
f = #(x, y) x.*y.^2;
Df = subs(diff(f,y),y,2);
Int = integral(Df , 0 , 1),
but I get the following error.
Error using integral (line 82)
First input argument must be a function
handle.
Can anyone help me in writing this code?
To solve the problem, matlabFunction was required. The solution looks like this:
syms x y
f = #(x, y) x.*y.^2;
Df = matlabFunction(subs(diff(f,y),y,2));
Int = integral(Df , 0 , 1);
Keeping it all symbolic, using sym/int:
syms x y;
f = #(x, y) x.*y.^2;
Df = diff(f,y);
s = int(Df,x,0,1)
which returns y. You can substitute 2 in for y here or earlier as you did in your question. Not that this will give you an exact answer in this case with no floating-point error, as opposed to integral which calculated the integral numerically.
When Googling for functions in Matlab, make sure to pay attention what toolbox they are in and what classes (datatypes) they support for their arguments. In some cases there are overloaded versions with the same name, but in others, you may need to look around for a different method (or devise your own).

why isn't the result a scalar?

i'm stuck with this error:
In an assignment A(I) = B, the number of elements in B and I must be the same.
yres(1)=((u - uc).^2) + ((y - yc).^2) -(d.^2);
i don't understand, why this won't get a skalar?since the elements are all scalar. what should be changed to get a scalar?
best regards
edit: thanks sloede, all inputs are scalar, but i still get this error
In an assignment A(I) = B, the number of elements in B and I must be the
same.
Error in myfun (line 7)
yres(1)=sqrt(((u - uc).^2) + ((y - yc).^2) ) -d;
Error in fsolve (line 241)
fuser = feval(funfcn{3},x,varargin{:});
Error in modfsolve (line 26)
x= fsolve(#myfun,x0,options,uc,d,spacing_amplitude,spacing_width);
Caused by:
Failure in initial user-supplied objective function evaluation. FSOLVE
cannot continue.*
The "." before an operator means that the following operation should be applied element-wise and not on the vector as a whole. Thus
a = b.^2
will give you as a result all elements of b squared and saved back to a. Therefore, in your code statement above, if any of u, uc, y, yc, d are not scalar but a vector, your result will be a vector as well.
Otherwise there seems to be nothing wrong with your code.
read the documentation of fsolve: http://www.mathworks.nl/help/toolbox/optim/ug/fsolve.html
it states:
fun
The nonlinear system of equations to solve. fun is a function that accepts a vector x and returns a vector F, the nonlinear equations evaluated at x.
Obviously your function myfun doesn't handle vector input.
You can solve this by adding the following construction inside your function (and of course change it to your needs/your parameters):
function out = myfun(in)
if ~isscalar(in)
% assuming it's a matrix or vector
out = reshape(arrayfun(#myfun,in(:)),size(in));
else
% your actual function execution statements
out = dostuffon(in);
end
end
or properly vectorize your function (if that's possible)