How to enter subscripts in matlab? for a loop
3 views (last 30 days)
Show older comments
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?
0 Comments
Answers (2)
Walter Roberson
on 9 Oct 2019
Edited: Walter Roberson
on 9 Oct 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
0 Comments
Shubham Gupta
on 9 Oct 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);
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!