How to enter subscripts in matlab? for a loop

2 visualizaciones (últimos 30 días)
Beca J
Beca J el 9 de Oct. de 2019
Respondida: Shubham Gupta el 9 de Oct. de 2019
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?

Respuestas (2)

Walter Roberson
Walter Roberson el 9 de Oct. de 2019
Editada: Walter Roberson el 9 de Oct. de 2019
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 el 9 de Oct. de 2019
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);

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by