假設我有一個函數f(x) = cos(x)
。我想評估f(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)
for循環中的函數求和(matlab)
我寫下面的代碼,但它沒有給出總計(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)'is)你可以使用矢量值作爲你的輸入,然後求和結果,從而在一行代碼中完成這個任務:'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)' –