Reputation: 2276
I need to evaluate the integral from x=-1
to x=1
for the function x*e^(x)*sin(pi*x)
. To do so, I'm using the Gaussian Quadrature method. This method can be summarized as the summation of the (weights)*(function evaluated at given roots)
from k=1
to k=n
where n=30
.
In my code below, the roots are found in the column vector LegendreGaussQuadratureConstants(n).x
. I'm taking the transpose because I want to perform element by element multiplication on the weights, which are stored in the row vector LegendreGaussQuadratureConstants(n).w
My code:
fx = @(x) x .* e.^(-x) .* sin(pi .* x);
for k = 1:50
Leg(k) = (fx(LegendreGaussQuadratureConstants(k).x))' .* LegendreGaussQuadratureConstants(k).w;
endfor
The problem is that it's giving me the error in the title, implying that there is some problem with using a scalar value of k
and that it should match up with the size of values being multiplied, but that makes no sense...
Upvotes: 3
Views: 4639
Reputation: 65460
You said it yourself in your question
the roots are found in the column vector
LegendreGaussQuadratureConstants(n).x
. I'm taking the transpose because I want to perform element by element multiplication on the weights, which are stored in the row vectorLegendreGaussQuadratureConstants(n).w
.
You're taking the element-wise product of two vectors and the result is also going to be a vector. However, you then try to assign it to a scalar, Leg(k)
which produces your error.
You either need to store these vectors in a 2D version of Leg
for k = 1:50
Leg(k,:) = (fx(LegendreGaussQuadratureConstants(k).x))' .* LegendreGaussQuadratureConstants(k).w;
endfor
or perform some other operation on the element-wise multiplication result to get it to be a scalar.
for k = 1:50
Leg(k) = sum((fx(LegendreGaussQuadratureConstants(k).x))' .* LegendreGaussQuadratureConstants(k).w);
endfor
Upvotes: 2