Preallocating and filling long array with shorter arrays

6 次查看(过去 30 天)
Hello dear community,
I have a question:
If I want to fll an array with single values using preallocation, I do:
input = zeros(1,1000000);
for k = 2:1000000
input(k) = input(k-1) + 5; % 5 is a newdata value in this example
end
so, in input will be stored values 0, 5, 10, 15, 20....
*********************************************************************
now, I have a data input from arrays (ex.) 5 values long, and I want to concatenate them to one big input array after every loop:
newdata:
4 5 7 8 9, 5 8 7 9 5, 1 7 8 9 6, 1 2 3 6 5
to one array input in few steps:
4 5 7 8 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
............
4 5 7 8 9 5 8 7 9 5 1 7 8 9 6 1 2 3 6 5
If I create a big zeroarray, and then create an input variable in a loop, I just create every time a new variable in a loop. How can I use the method from single variable by arrays to use preallocation?
input = [zeros(20,[])]; %it has no sence
for i = 1 : total_frames
input = [input;newdata];
end
Thank you!
P.S. Actually, I'm working with big arrays (48000 * 100000000), the short example is just for better understanding. I want to make my algorithm time efficient.

采纳的回答

Stephen23
Stephen23 2023-3-20
编辑:Stephen23 2023-3-20
The simple apparoach is to use a matrix or array, for example:
N = 10;
M = nan(5,N);
for k = 1:N
M(:,k) = rand(5,1);
end
display(M)
M = 5×10
0.5932 0.1375 0.9838 0.9635 0.7082 0.7918 0.3489 0.1323 0.9478 0.5962 0.6731 0.8178 0.3265 0.6184 0.2314 0.0253 0.0699 0.5711 0.7934 0.5818 0.8518 0.1121 0.2469 0.3151 0.5395 0.7872 0.9489 0.0019 0.1219 0.3131 0.3972 0.2027 0.3039 0.0395 0.6487 0.6918 0.8420 0.1117 0.2279 0.0301 0.5613 0.1273 0.4150 0.2947 0.1517 0.5669 0.3289 0.1059 0.8498 0.1112
"Actually, I'm working with big arrays (48000 * 100000000)"
  1 个评论
Nik Rocky
Nik Rocky 2023-3-21
Great answer, thank you very much!
Here is comparsion old to new:
spf = 48000;
frames = 200;
data=[nan(spf*frames,[])];
tic
for k = 1 : frames
input = rand(48000,1);
data = [data;input];
end
toc
Elapsed time is 3.206472 seconds.
spf = 48000;
frames = 200;
data = nan(spf,frames);
tic
for k = 1:frames
data(:,k) = rand(spf,1);
end
data = reshape(data.', [],1);
toc
Elapsed time is 0.093135 seconds.
In the end I have a big (spf*frames) x 1 array, that I need
Feel the difference =)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by