フィルターのクリア

How do I create (and retain) the elements of vectors using for loop?

2 ビュー (過去 30 日間)
Rinu
Rinu 2013 年 10 月 6 日
コメント済み: Jan 2013 年 10 月 8 日
I want a function file to output two vectors 'pi_estimate' and 'error' of length 'n' each. I'm initializing the vectors with zeros(1,n) and then using a for loop to create the elements of the vectors, but, in the output, I get only the last elements (all other elements are zero). It seems like all the elements other than the last ones aren't retained while carrying out the for loop. Any help is much appreciated. Here's my code:
function [pi_estimate,error]=pi_estimate(n)
%function [pi_estimate,error]=pi_estimate(n)
%This m-file estimates the value of pi in 'n' iterations
a=1;
b=6;
pi_estimate=zeros(1,n);
error=zeros(1,n);
for i=1:n
b=2*b;
a=(2-(4-a^2)^0.5)^0.5;
L=a*b/2;
u=L/(1-a^2/2)^0.5;
pi_estimate(1,n)=(u+L)/2;
error(1,n)=(u-L)/2;
end
end
  1 件のコメント
Jan
Jan 2013 年 10 月 8 日
sqrt() is more efficient than the more general ^0.5 .

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

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 10 月 6 日
編集済み: Azzi Abdelmalek 2013 年 10 月 6 日
You have used n instead of i
pi_estimate(1,i)=(u+L)/2;
error(1,i)=(u-L)/2;
  1 件のコメント
Rinu
Rinu 2013 年 10 月 6 日
Oh that was such a silly mistake. Thank you so much though. I spent hours trying to figure out what was wrong :)

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

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by