如何用for循环的答案填充零向量?

时间:2019-11-27 17:16:18

标签: matlab octave

我创建了一个零向量

result = zeros(1,20);

在GNU Octave GUI上,我想用for循环的积分估计值填充零。

a = 0;
b = 3;
f = @(x) sin(10 *x.^2);

for i = 20
    n = 2.^i;
    dx = (b - a) / n;
    left = a:dx: (b - dx);
    right = (a+dx) :dx:b;
    h1 = f(left);
    h2 = f(right);
    areas = (h1 + h2) ./ 2 .* dx;
    totalarea = sum(areas)
endfor

有人可以告诉我如何用上面的for循环中的result值填充totalarea矩阵吗?

1 个答案:

答案 0 :(得分:1)

查看评论:

result = zeros(1,20);
a = 0;
b = 3;
f = @(x) sin(10 *x.^2);

for i = 1:20 % make sure you loop from 1 to 20
    n = 2.^i; 
    dx = (b - a) / n;
    left = a:dx: (b - dx);
    right = (a+dx) :dx:b;
    h1 = f(left);
    h2 = f(right);
    areas = (h1 + h2) ./ 2 .* dx;
    totalarea = sum(areas);
    result(i) = totalarea; % put the totalarea in the i'th position in the result matrix
endfor