How I can optimize my code for a stack construct?

조회 수: 1 (최근 30일)
Nazar Adamchuk
Nazar Adamchuk 2021년 4월 19일
댓글: Rik 2021년 4월 19일
In reality I have nine variables with scalar values. For them, I have built a stack construct (last in first out) with following logic: push (only for three variabled from nine, as an example)
stack(end+1:end+3) = [value1, value2, value3];
read and pop is
value3 = stack(end); stack = [];
value2 = stack(end); stack = [];
value1 = stack(end); stack = [];
In my script I call these code lines over 8 million time each and that is why I wish the time could be less. Can you help me to optimize the code lines and decrease the speed?

답변 (1개)

Rik
Rik 2021년 4월 19일
Dynamically growing a variable is generally slow, because Matlab needs to copy the entire array.
You could pre-allocate a stack and use a counter to keep track of the position in the stack.
  댓글 수: 2
Nazar Adamchuk
Nazar Adamchuk 2021년 4월 19일
I am not copying the array, I am appending the elements to the array. That would be copying:
stack = [stack value1 value2 value3]
Rik
Rik 2021년 4월 19일
Matlab is copying the array for you: if you add an element to a vector Matlab will allocate a new block of memory, copy all the data (appending your new elements), and free the old memory blocks.
%these two operations are the exact same:
stack(end+1:end+3) = [value1, value2, value3];
stack = [stack, value1, value2, value3];

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Get Started with Optimization Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by