How to enter subscripts in matlab? for a loop

8 次查看(过去 30 天)
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
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
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);

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by