for loop

5 ビュー (過去 30 日間)
Liam Mescall
Liam Mescall 2011 年 9 月 9 日
Hi,I have created the following loop:
for i = 1:5 x = i*2 end
I wish to be able to record each value of the iteration i.e. 2,4,6,8,10 aswell as arrive at the final value of 10 which the above code dies.Could you tell me how to do this? Thanks

採用された回答

Grzegorz Knor
Grzegorz Knor 2011 年 9 月 9 日
x = zeros(5,1);
for i = 1:5
x(i) = i*2;
end
disp(x)

その他の回答 (3 件)

Andrei Bobrov
Andrei Bobrov 2011 年 9 月 9 日
for i1 = 5:-1:1, x(i1) = i1*2;end
for your case
x = (1:5)*2
or
x = 2:2:10
  3 件のコメント
Andrei Bobrov
Andrei Bobrov 2011 年 9 月 9 日
Hi Grzegorz! I begin with last number 'x' and this way preallocate memory. Please read this http://www.mathworks.com/matlabcentral/answers/7039-how-to-multiply-a-vector-with-each-column-of-a-matrix-most-efficiently
Grzegorz Knor
Grzegorz Knor 2011 年 9 月 9 日
nice trick :)

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


mohammad
mohammad 2011 年 9 月 9 日
x=[];
for i = 1:5
x =[x;i*2]; %for column matrix
end
OR:
x=[];
for i = 1:5
x =[x,i*2]; %for row matrix
end
  2 件のコメント
Andrei Bobrov
Andrei Bobrov 2011 年 9 月 9 日
Hi mohammad! Please read this http://www.mathworks.com/help/techdoc/matlab_prog/f8-784135.html#f8-793781
Jan
Jan 2011 年 9 月 9 日
This is working and fast for tiny vectors. But it is really worth to pre-allocate arrays to get familiar with good programming methods. Without pre-allocation, this happens:
1. x is created as empty DOUBLE vector. This needs about 100 bytes for the internal header and 0 bytes for the data.
2. Inside the loop another vector x is created, again 100 bytes header, 8 bytes for the data. The former x is released.
3. In the 2nd iteration the next vector is created, again 100 bytes header, 16 bytes of data, 8 bytes of the formar array are copied. The former x is released.
4. etc.
If the loop runs until N, a total of N*100+prod(1:N)*8 bytes are allocated, filled with zeros, partially released later and prod(1:N-1)*8 bytes are copied.
In consequence you apporach is horribly slow for e.g. 1000 elements and might even crash with an out-of-memory error for larger vectors. Therefore *always* pre-allocate.

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


Liam Mescall
Liam Mescall 2011 年 9 月 9 日
Thanks guys

カテゴリ

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