How to access zero index in the following code?

4 ビュー (過去 30 日間)
Abhinav
Abhinav 2016 年 12 月 5 日
回答済み: Steven Lord 2016 年 12 月 5 日
I need to calculate value of tol for i=1:20
tol=abs(hvq(i))-abs(hvq(i-1))
Now in the first iteration as it is giving me error saying, "attempted to access hvq(0); index must be a positive integer or logical". I know that MATLAB is not based on zero indexing. Now how to resolve this issue? In the first iteration 'abs(hvq(i-1))' should take value =0.
  1 件のコメント
Stephen23
Stephen23 2016 年 12 月 5 日
This is unrelated to one/zero based indexing. The question is simply how to specify the index before the first index. The answer is simply: don't, because it does not exist (not matter whether one or zero based).

サインインしてコメントする。

採用された回答

John D'Errico
John D'Errico 2016 年 12 月 5 日
編集済み: John D'Errico 2016 年 12 月 5 日
Do you mean that you cannot use an if test? It is not possible to test for when i==1, and use a slightly different formula? Hmm. I thought that was possible. :)
The point being, just use a test.
if i == 1
altered forula for tol
else
usual formula
end
Since you will use a loop to do this anyway, this will work.
  1 件のコメント
Abhinav
Abhinav 2016 年 12 月 5 日
編集済み: Abhinav 2016 年 12 月 5 日
Thank you :) It worked!

サインインしてコメントする。

その他の回答 (1 件)

Steven Lord
Steven Lord 2016 年 12 月 5 日
Compute the absolute value of the whole vector first. Concatenate a 0 at the start of the vector then use diff.
x = (1:10).^2;
dx = diff([0 abs(x)]);
result = [x; dx]
Each element in the second row of result is the difference between the element immediately above it in the first row and the element immediately before that one in the first row. The only exception is the first element in the second row, which is the same as the element above it in the first row (minus 0, which rarely makes a difference.)

カテゴリ

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