필터 지우기
필터 지우기

About preallocating for speed

조회 수: 2 (최근 30일)
Saf el
Saf el 2017년 11월 30일
편집: James Tursa 2017년 11월 30일
There is a " for loop" in my program and Matlab gives me a suggestion to consider "Preallocating" for speed. I want to learn how to do it. This is my code:
A = [];
for i = 1:size(P,2)
Ai = build_matrix(P(:,i));
*A* = [A; Ai];
end
there is a red line under A on Bold saying that The size of the indicated variable or array appears to be changing with each loop iteration. Could you guys tell me what should I do to solve it. Thanks!!

채택된 답변

James Tursa
James Tursa 2017년 11월 30일
편집: James Tursa 2017년 11월 30일
This depends on what the size and class of the matrix returned by build_matrix( ) is. E.g., suppose it returns an MxN double matrix. Then the pre-allocation and the assignments would look like this:
A = zeros(size(P,2)*M,N); % pre-allocate result
for i = 1:size(P,2)
A(1+(i-1)*M:i*M,:) = build_matrix(P(:,i)); % modify the way you do the assignment
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by