avoid negative index in array or matrix

1 回表示 (過去 30 日間)
Damiano Capocci
Damiano Capocci 2017 年 12 月 17 日
回答済み: Damiano Capocci 2017 年 12 月 17 日
I'm working on 2 loops in which i have the difference of two indices like this:
for i=1:interval_1
for j=0:interval_2
if(i-j>0)
X(i+1)=c(j+1)*X(i-j);
else
%nothing
end
end
In my situation interval_1 and interval_2 are more or less 1 million so i want to optimize and remove if/else. It would be useful if there exist a command which ignores operations with negative index. Tell me.
  2 件のコメント
Stephen23
Stephen23 2017 年 12 月 17 日
編集済み: Stephen23 2017 年 12 月 17 日
Use
if
Or change the loop index range.
David Goodmanson
David Goodmanson 2017 年 12 月 17 日
Hi Damiano, it looks like the j loop is overwriting X(i+1) every time, with the effect that the loop collapses down to the single j value min(interval_2,i-1).

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

採用された回答

Roger Stafford
Roger Stafford 2017 年 12 月 17 日
Just do this:
for i=1:interval_1
j = min(i-1,i2);
X(i+1)=c(j+1)*X(i-j);
end

その他の回答 (2 件)

Jos (10584)
Jos (10584) 2017 年 12 月 17 日
Why not switch the loops, and let i start from j+1
for j=0:interval_2
for i=j+1:interval_1
% if(i-j>0) % this is now always true
X(i+1)=c(j+1)*X(i-j);
% else
% %nothing
% end
end
end
And then you also see immediately that X(i+1) gets overwritten all the time (as David pointed out) and X(1) is never calculated ...

Damiano Capocci
Damiano Capocci 2017 年 12 月 17 日
Yes, all of u are right in particular david, my code is a bit complex so i've tried to explain the question giving the idea of my code but i've made a mistake. (I think) The best solution of my problem is
for k=1:interval_1 for p=0:(k-1,interval_2)
x(k+1)=x(k+1)+c(p+1)*x(k-p)
end end
tic toc gives a little improvement but however it is always a function called every step

カテゴリ

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