Setting variable to zero with conditional statement?

I'm writing a for loop which runs through values and sometimes the element that the loop selects is outwith the vector length.
For example, say I have a vector of 10 entries and the loop asks for the 11 "th" entry it doesn't exist so I get an error.
How do I put this in the code with an if statement? I want the code to go like:
%the loop selects y(n)
if n>10 then set y(n) = 0
else y(n) = y(n)
Sorry if it's unclear, I'm sure it's a simple fix?

2 件のコメント

Jose Marques
Jose Marques 2017 年 11 月 19 日
Could you post your entire code? So we can help you better
matlabkid602
matlabkid602 2017 年 11 月 19 日
編集済み: Walter Roberson 2017 年 11 月 19 日
shift = k-n;
if shift <1 || shift >21
y(shift) = 0;
end

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

回答 (1 件)

Walter Roberson
Walter Roberson 2017 年 11 月 19 日

1 投票

if n>length(y); y(n) = 0; end

3 件のコメント

matlabkid602
matlabkid602 2017 年 11 月 19 日
Subscript indices must either be real positive integers or logicals.
n can be positive or negative. This doesn't work.
How can this be done on Matlab?
Walter Roberson
Walter Roberson 2017 年 11 月 19 日
If I understand correctly, for negative shift you would like to set array locations with negative indices? That is not permitted in MATLAB. Do you want negative shift to be interpreted as starting from the maximum value, with n = -1 being interpreted the same as y(end) and n = -2 being interpreted the same as y(end-1) ?
matlabkid602
matlabkid602 2017 年 11 月 19 日
編集済み: matlabkid602 2017 年 11 月 19 日
If I choose k such that somewhere during the loop "shift" becomes negative, or greater than the length of y, I want y(shift) = 0.
I'm solving ODE's with the loop and need this condition.

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

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

質問済み:

2017 年 11 月 19 日

編集済み:

2017 年 11 月 19 日

Community Treasure Hunt

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

Start Hunting!

Translated by