gstrutz
gstrutz

Reputation: 11

MATLAB vectorized code return wrong result

I'm taking a MATLAB course and have written the following code. One is a FOR LOOP and the other is a vectorization. The FOR LOOP returns the correct result but the vectorization does not. Can anyone tell me what I have coded incorrectly?

Should be for the following equation.

1 - 1/3 + 1/5 - 1/7 + 1/9 - ... - 1/1003 (sum is 0.7849 - converges slowly to pi/4)

USE FOR LOOP

clc
clear
tic
sign = -1;
y=0;
for x=1:2:1003
    sign=-sign;
    y=y+sign/x;
end

disp(['For Loop calculated ' num2str(y), ' and ran for ' num2str(toc)])

USE VECTORIZATION

clear
tic
n=1:2:1003;
x=sum(1./n -1./(n+2));
disp(['Vectorization calculated ' num2str(x), ' and ran for ' num2str(toc)])

Upvotes: 1

Views: 219

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112669

In the vectorized code, replace the x line by this:

x = sum(1./n .* (-1).^(0:numel(n)-1))

The term after 1./n takes care of the alternating sign.

As it stands now, your code sum(1./n -1./(n+2)) is giving you 1+1/3+1/5+...+1/1003 - (1/3+1/5+...+1/1005), that is (after cancellation of terms), 1-1/1005.

Upvotes: 2

gnovice
gnovice

Reputation: 125854

You could either change the formula you use in your summation (as suggested by Luis), or you could keep your formula and just change the step size you take in your n vector to this:

n = 1:4:1003;

Upvotes: 2

Related Questions