[英]Octave: For-loop error says A(I) = X: X must have the same size as I
I need to evaluate the integral from x=-1
to x=1
for the function x*e^(x)*sin(pi*x)
. 我需要为函数x*e^(x)*sin(pi*x)
计算从x=-1
到x=1
的积分。 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
. 该方法可以概括为从( k=1
到k=n
其中n=30
(weights)*(function evaluated at given roots)
的(weights)*(function evaluated at given roots)
的总和。
In my code below, the roots are found in the column vector LegendreGaussQuadratureConstants(n).x
. 在我的下面的代码中,根在列向量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
我正在进行转置,因为我想对权重进行逐元素乘法,这些权重存储在行向量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... 问题是它给了我标题中的错误,暗示使用标量值k
存在一些问题,并且它应该与乘以的值的大小相匹配,但这没有意义......
You said it yourself in your question 你在问题中自己说过
the roots are found in the column vector
LegendreGaussQuadratureConstants(n).x
. 根在列向量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
. 我正在进行转置,因为我想对权重进行逐元素乘法 ,权重存储在行向量LegendreGaussQuadratureConstants(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. 但是,然后尝试将其分配给标量Leg(k)
,它会产生错误。
You either need to store these vectors in a 2D version of Leg
您需要将这些矢量存储在Leg
版本的2D版本中
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.