Matrix size error using integral

2 次查看(过去 30 天)
I am currently trying to compute the Fourier coefficients of a function f(x). For the first coeffficient, I can use integral(f,-l,l) and have no problem with that. For the next coefficient, I define another function which is basically the same as f multiplied by a cos(x). However, if I try integral(f2,-x,x) I get an "Incorrect dimensions for matrix multiplication" error message, which makes no sense since I'm multiplying scalars. Why is this? How can I fix it?
(a,b,k,I0,t,cte are constants previously set)
fun=@(x) sqrt(exp((-(k*a*I0*2*(1+cos(cte*x))/(b+a*2*I0*(1+cos(cte*x)))))*(1-exp(-t(i)*(b+2*a*I0*(1+cos(cte*x)))))));
fun2=@(x) cos(cte*x);
fun3=@(x) fun(x)*fun2(x);
integral(fun3,-1e-7,1e-7)
Error using *
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of rows in
the second matrix. To operate on each element of the matrix individually, use TIMES (.*) for elementwise multiplication.
Error in fourier>@(x)fun(x)*fun2(x) (line 10)
fun3=@(x) fun(x)*fun2(x);
^

采纳的回答

Stephen23
Stephen23 2025-4-8
编辑:Stephen23 2025-4-8
"which makes no sense since I'm multiplying scalars."
Nope, you aren't.
"Why is this?"
Because you are multiplying vectors. The INTEGRAL documentation states "For scalar-valued problems, the function y = fun(x) must accept a vector argument, x, and return a vector result, y. This generally means that fun must use array operators instead of matrix operators. For example, use .* (times) rather than * (mtimes)." The same documentation also states one solution to this: "If you set the 'ArrayValued' option to true, then fun must accept a scalar and return an array of fixed size."
Lets try following what the documentation advises:
[a,b,k,I0,t,cte] = deal(1);
fun=@(x) sqrt(exp((-(k*a*I0*2*(1+cos(cte*x))/(b+a*2*I0*(1+cos(cte*x)))))*(1-exp(-t*(i)*(b+2*a*I0*(1+cos(cte*x)))))));
fun2=@(x) cos(cte*x); % check this ^
fun3=@(x) fun(x)*fun2(x);
integral(fun3,-1e-7,1e-7, 'ArrayValued',true)
ans = 1.3926e-07 + 5.6199e-08i
Alternatively you could write the function to accept a vector, just as the documentation describes.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Operators and Elementary Operations 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by