How to enter subscripts in matlab? for a loop

Hello,
I would like to create a for loop function that will estimate the square root of a number. I am stuck on a specific point, and here is a hypothetical situation.
I know that X0 = 1 and that the next term....X1... will be X1 = xi + 5/xi
This comes from a for loop of
for i = 0:5
x(i+1) = xi + 5/xi .... and repeat although I cannot use x(i) or x(0) because i get an error so how could i do this?

답변 (2개)

Walter Roberson
Walter Roberson 2019년 10월 9일
편집: Walter Roberson 2019년 10월 9일

0 개 추천

MATLAB subscripts must be positive integers. You will need to add 1 to your subscripts.
x(0+1) = 1;
for i = 0:5
x(i+1+1) = x(i+1) + 5/x(i+1);
end
Most of the time it is easier to just shift the numbering by 1 mentally
x(1) = 1;
for i = 1 : 6
x(i+1) = x(i) + 5/x(i);
end
Shubham Gupta
Shubham Gupta 2019년 10월 9일

0 개 추천

Simply shift your indeces by 1 i.e. x0 becomes x1, x1 becomes x2 and so on.
N = 500;
x = zeros(N+1,1);
x0 = 1;
x(0+1) = x0; % 0 shifted to 1
for i = 1:N
x(i+1) = x(i) + 5/x(i); % gives x(2), x(3), ..., x(N+1) which are equivalent to x1, x2, ..., xN
end
Next, if you want accesss particular index. You can do :
ind = 30; % for e.g. you want x30
x30 = x(ind+1);

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2019년 10월 9일

답변:

2019년 10월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by