Question about to reconduct [for loop statement] to the code using vectorization

1 回表示 (過去 30 日間)
N/A
N/A 2022 年 10 月 26 日
編集済み: N/A 2022 年 10 月 26 日
hello
first i made the code that he answer to the following expression is 0.7849
its expression is
the code i made is (result is 0.7849)
sum=0;
for m=0:2:10000000
k=m;
i=m+1;
sumx=(1/(2*k+1));
sumy=(-1/(2*i+1));
sum=sumx+sumy+sum
end
-----------------------------------------------------------------------------------------------
So, What I want to do is to reconstruct the code above using vectorization.(use ./ .*) (not using for loop statement)
i made this, but it works strangely.(I don't know if I made it right)
format short
sum=0;
m=0:2:500;
k=m;
i=m+1;
sumx=(1./(2*k+1));
sumy=(-1./(2*i+1));
sum=sumx+sumy+sum
Should I write more variable?
How do I reconstruct it right?
  2 件のコメント
VBBV
VBBV 2022 年 10 月 26 日
format short
sumi=0; % sum is builtin function of matlab
m=0:2:500;
k=m;
i=m+1;
sumx=sum((1./(2*k+1))); % apply the sum function to the series
sumy=sum((-1./(2*i+1))); % sum the series
Sum=sumx+sumy+sumi
Sum = 0.7849
sum is a builtin function in matlab, variables are usually named that doesnt conflict with standard builtin functions in matlab,
N/A
N/A 2022 年 10 月 26 日
編集済み: N/A 2022 年 10 月 26 日
i did simillar as you did, but it didnt work because i used 'sum' function as it.
after seeing this, i found my fault.
thanks!

サインインしてコメントする。

採用された回答

David Hill
David Hill 2022 年 10 月 26 日
format long
s=sum(1./(2*(0:2:500)+1)-1./(2*(1:2:501)+1))
s =
0.784900155923366

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by