Basic question about initializing variables
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
What's the difference between
a = [ 1 2 3 ];
and
a = zeros(1,3);
a = [ 1 2 3 ];
Performance? Logic? I'm just interested to know. Thanks for your help!
채택된 답변
Jan
2017년 4월 20일
In
a = zeros(1,3);
a = [ 1 2 3 ];
Matlab reserves memory for 3 doubles and fills then with zeros in the first line. In the second line this memory is freed and a new vector is created. This needs about the double work compared to creating [1, 2, 3] directly and in consequence is a waste of time only.
This is not a pre-allocation. A pre-allocation would mean, that the reserved memory is re-used later:
a = zeros(1, 3);
a(1) = 1;
a(2) = 2;
a(3) = 3;
or
a = zeros(1, 3);
a(:) = 1:3;
The "(:)" is essential here, because it tells Matlab to overwrite the contents of the formerly existing memory.
댓글 수: 6
Ahmed Hossam
2017년 4월 20일
편집: Ahmed Hossam
2017년 4월 20일
So, in matlab I don't need to wory about pre-allocation and just write my one line of code?
Ahmed Hossam
2017년 4월 20일
편집: Ahmed Hossam
2017년 4월 20일
Use the appropriate preallocation function for the kind of array you want to initialize:
zeros for numeric arrays
cell for character arrays
https://ch.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html
@Ahmed Hossam: You are confusing different topics together.
You should preallocate arrays whenever the array would otherwise be repeatedly expanded (for example before any loop): this significantly improves performance (but it is not a fatal error without it). This is what that help page is explaining, which its very first line clearly states: "for and while loops that incrementally increase the size of a data structure each time through the loop can adversely affect performance and memory use"
However this has nothing to do with your question (which does not mention loops, and does not incrementally expand any array). And as such Jan Simon correctly answered your question (which is not about array preallocation required before loops).
a = [];
for k = 1:1e6
a(k) = k;
end
This is allowed in Matlab. Even if a is removed by clear a before the loop, Matlab runs fine. But the iterative growing of the arrays is very expensive: In the first iteration, Matlab reserves memory for 1 double (8 bytes) and assigns the value to the first element. In the next iteration, memory for 1 doubles is reserved, the first element is copied, the former array is released and the new value is copied. Finally, Matlab has reverved and copies not 1e6*8 bytes (8 MB), but sum(1:1e6)*8 bytes: 4 TB! This takes time. With a proper pre-allocation only 8MB are used:
a = zeros(1, 1e6);
for k = 1:1e6
a(k) = k;
end
Thank you for your help
Ahmed Hossam
2017년 4월 20일
편집: Ahmed Hossam
2017년 4월 20일
@ Stephen Cobeldick:
Ok, I understand both topics now.
First topic:
Just deklare and initialize a variable in one line! (beautiful feature!!)
Second topic:
Don't extend the memory of a variable in a loop!
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
