【问题标题】:Summation of function in a for loop (matlab)for循环中的函数求和(matlab)
【发布时间】:2017-01-23 20:53:15
【问题描述】:

假设我有一个函数f(x) = cos(x)。我想以g(x) = 1/2*f(0) + sum(1/4*f(a+h*i)) (for i is odd) + sum(3/4*f(a+h*i)) (for i is even except 0 and 10) + 1/2*f(b) 的形式评估f(x)

我写了下面的代码,但它没有给出(1/4*f(a+h*i)(for i is odd)的总和和3/4*f(a+h*i)(for i is even except 0 and 10)的总和。

a=0
h=0.1571
n=10
b=1.5708
for i = 1: n
    simp_int2 = 0;
    simp_int3 = 0;
    simp_int1 = 1/2*f(0)
    if i < n
        if rem(i,2)~=0
            simp_int2 = simp_int2 + 1/4*f(a+h*i)
        end
        if rem(i,2)==0
            simp_int3 = simp_int3 + 3/4*f(a+h*i)
        end
    end
    simp_int4 = 1/2*f(b)
end
simp_int = simp_int1 + simp_int2 + simp_int3 + simp_int4

我也试过 cumsum 和 symsum。两者都没有按照我的预期工作。感谢您的帮助!

【问题讨论】:

  • 另外,如果你有一个向量化形式的函数(cos(x) 是),你可以只使用向量值作为输入并将结果求和,从而在一行代码中完成此任务:@ 987654328@

标签: matlab function for-loop sum


【解决方案1】:

由于您的函数将为向量输入返回向量输出,因此您可以在没有 for 循环的情况下执行此操作:

a=0
h=0.1571
n=10
b=1.5708
simp_int = 1/2*f(0) + sum(1/4*f(a + h*[1:2:n])) + sum(3/4*f(a+h*[2:2:n-1])) + 1/2*f(b)

【讨论】:

  • 谢谢! Rayryeng 帮我找到了问题!
【解决方案2】:

您在每次迭代时都重置累积变量。将 simp_* 初始化移到 for 循环之外。

具体来说:

a=0
h=0.1571
n=10
b=1.5708
% Change
simp_int1 = 1/2*f(0);
simp_int2 = 0;
simp_int3 = 0;        
simp_int4 = 1/2*f(b);
for i = 1: n
    if i < n
        if rem(i,2)~=0
            simp_int2 = simp_int2 + 1/4*f(a+h*i)
        end
        if rem(i,2)==0
            simp_int3 = simp_int3 + 3/4*f(a+h*i)
        end
    end
end
simp_int = simp_int1 + simp_int2 + simp_int3 + simp_int4;

【讨论】:

  • @Orangeblue 哈哈没问题:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-05
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
相关资源
最近更新 更多