简体   繁体   中英

Summation of function in a for loop (matlab)

Suppose I have a function f(x) = cos(x) . I want to evaluate f(x) in a form of 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)

I write the code below, but it did not give the sum of (1/4*f(a+h*i)(for i is odd) and the sum of 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

I also tried cumsum and symsum. Both not working the way I intended. Thanks for any help!

You are resetting the accumulation variables at every iteration. Move the simp_* initializations to outside of the for loop.

Specifically:

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;

Since your function will return vector output for vector input you can do this without a for loop:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM