필터 지우기
필터 지우기

Basic question about initializing variables

조회 수: 4 (최근 30일)
Ahmed Hossam
Ahmed Hossam 2017년 4월 20일
편집: Ahmed Hossam 2017년 4월 20일
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
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
Ahmed Hossam 2017년 4월 20일
Thank you for your help
Ahmed Hossam
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개)

카테고리

Help CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by