Question about to reconduct [for loop statement] to the code using vectorization
1 次查看(过去 30 天)
显示 更早的评论
hello
first i made the code that he answer to the following expression is 0.7849
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1169498/image.png)
its expression is
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1169503/image.png)
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
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 is a builtin function in matlab, variables are usually named that doesnt conflict with standard builtin functions in matlab,
采纳的回答
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!