【发布时间】: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