How to enter subscripts in matlab? for a loop

3 ビュー (過去 30 日間)
Beca J
Beca J 2019 年 10 月 9 日
回答済み: Shubham Gupta 2019 年 10 月 9 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by