How can I add elements to pre-allocated array?

조회 수: 18 (최근 30일)
Erik Hricka
Erik Hricka 2018년 3월 9일
댓글: Stephen23 2018년 3월 9일
I used "Data = zeros(1,100);" but I want to replace zeros with values in cycle like this:
for i = 1 : 10
var1 = "somefunctionthatgives(1,10)vector"
Data = [Data,var1];
end
Without allocation is runs just perfectly but MATLAB keeps suggesting to pre-allocate array for speed... I would normally ignore it but I have to solve task in which at the end variable Data would be vector (1,10000000). And doing it in minimum time is also part of the task. Can somebody help me?
Thanks a lot...
  댓글 수: 2
Von Duesenberg
Von Duesenberg 2018년 3월 9일
Just a hint in pseudo-code : Data(1:10) = var1
Stephen23
Stephen23 2018년 3월 9일
"MATLAB keeps suggesting to pre-allocate array for speed..."
Always write code using good code practices.
When someone writes code only using inefficient/buggy practices, then they will learn and practice only those methods. And then when one day it becomes critical to write something better, they will have no experience or idea how to write efficient code.
Writing preallocated code also means that the code is more generalized, so that even if it was tested with ten elements it will work happily with ten million. Why limit the code for no reason?
"I would normally ignore it"
Never ignore the hints from the editor.

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

답변 (1개)

Von Duesenberg
Von Duesenberg 2018년 3월 9일
Try this:
Data = zeros(100,1);
i = 1;
while i < length(Data)
var1 = randperm(10);
currentIdx = (0:9)+i;
Data(currentIdx) = var1;
i = i + 10;
end

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by