필터 지우기
필터 지우기

Hi! I have a problem in my function, Error in MATLAB

조회 수: 1 (최근 30일)
Anthony Fuentes
Anthony Fuentes 2016년 10월 30일
답변: KSSV 2016년 10월 31일
Use Wellis product= pi/2=2/1∗2/3∗4/3∗4/5∗6/5∗ … in a function in MATLAB that receives the relative error willing to accept and return the user a vector with all values of π and other vector estimated with relative errors associated with each value of π. (This is in arrays). Thanks a lot. But, MATLAB gives me an error:
Attempted to access ret(0); index must be a positive integer or logical.
Error in pi_value (line 13)
ret(i) = 2 * (ret(i - 1) / 2) * temp;
The function is the following:
function[e, ret] = pi_value(err)
ret = [4];
value = 0;
e = inf;
i = 1;
while e > err
++i;
temp = 0;
if mod(i, 2) == 0
temp = i / (i + 1);
else
temp = (i + 1) / i;
end
ret(i) = 2 * (ret(i - 1) / 2) * temp;
e = abs(ret(i) - ret(i - 1));
end
end
Thanks a lot!
  댓글 수: 2
dpb
dpb 2016년 10월 30일
What is index of the RH ret value in
ret(i) = 2*(ret(i-1)/2)*temp;
?? Matlab arrays, as the error message says, only begin at 1. You'll have to special-case the end condition to avoid explicitly referencing a 'zeroth' element.
Also, note that numerically the expression as written above is simply
ret(i) = ret(i-1)*temp;
the two 2's cancel each other out...
John D'Errico
John D'Errico 2016년 10월 30일
Not that the code as posted is NOT valid MATLAB syntax.
++i;
NOT in MATLAB.

댓글을 달려면 로그인하십시오.

채택된 답변

KSSV
KSSV 2016년 10월 31일
function[e, ret] = pi_value(err)
ret = 4;
e = inf;
i = 1;
while e > err
i = i+1 ;
if mod(i, 2) == 0
temp = i / (i + 1);
else
temp = (i + 1) / i;
end
ret(i) = 2 * (ret(i - 1) / 2) * temp;
e = abs(ret(i) - ret(i - 1));
end
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by