How do I preallocate this loop?

1 回表示 (過去 30 日間)
Ryan
Ryan 2013 年 8 月 8 日
Hello
I'm trying to make my program run faster and it suggests to preallocate this loop. Anyone know how convert this loop?
% code
for i = 1:1:5
z(i) = x(zipfind - 1 + i);
end
Thanks!

採用された回答

Evan
Evan 2013 年 8 月 8 日
編集済み: Evan 2013 年 8 月 8 日
Here is the loop with preallocation:
z = zeros(5,1) % preallocation
for i = 1:1:5
z(i) = x(zipfind - 1 + i);
end
Also, it looks as if you could possibly remove the looping altogether:
x = randi(20,20,1);
zipfind = randi(20);
zloop = zeros(5,1);
for i = 1:5
zloop(i) = x(zipfind - 1 + i);
end
zvec = x(zipfind - 1 + (1:5));
And compare the results of zloop and zvec:
>>zvec
zvec =
14
4
3
10
20
>> zloop
zloop =
14
4
3
10
20
So, basically, you could just replace that entire loop with:
z = x(zipfind - 1 + (1:5));

その他の回答 (0 件)

カテゴリ

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