Preallocating a Matrix(For loop, Vectorization)?

2 ビュー (過去 30 日間)
ManvsMachine
ManvsMachine 2019 年 5 月 9 日
コメント済み: ManvsMachine 2019 年 5 月 9 日
I hear that preallocating a matrix before the for loop is efficeint , but why do i get the error " The value assigend to the variable might be unused", when used before vectorization ? Example code
%% Vectorization method
Y4=repmat(A,N,1);
Y4 = cell2mat(arrayfun(@(i) A^i, (1:N)', 'Uni', false)
%% Normal Multiplication method
Y5=repmat(A,N,1);
for i=1:N
Y5((i-1)*Dim+1:i*Dim,:)=A^i;
%disp i
end
  1 件のコメント
Stephen23
Stephen23 2019 年 5 月 9 日
Y4 = repmat(A,N,1); % This is NOT preallocation!
Y4 = ....
You are simply replacing one array with another array, which has nothing to do with preallocation. Preallocation requires specifying an entire array in memory before accessing parts of it using indexing (note that you are not using indexing into Y4).

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

採用された回答

James Tursa
James Tursa 2019 年 5 月 9 日
編集済み: James Tursa 2019 年 5 月 9 日
In these lines:
Y4=repmat(A,N,1);
Y4 = cell2mat(arrayfun(@(i) A^i, (1:N)', 'Uni', false)
The first line assigns something to Y4. The second line wipes out what you just assigned to Y4 in the first line and replaces it with something else from the second line. In other words, the first line is useless and the value assigned to Y4 in the first line is unused.
  3 件のコメント
Stephen23
Stephen23 2019 年 5 月 9 日
編集済み: Stephen23 2019 年 5 月 9 日
",could i make that 2line of code more efficeint?"
Not really: both cell2mat and arrayfun are relatively slow. The fastest solution is likely by using an expilcit loop with a preallocated output array.
ManvsMachine
ManvsMachine 2019 年 5 月 9 日
got it,appreciate that.thanks

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

その他の回答 (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