how can I modify a triple "for" cycle to run faster?

1 view (last 30 days)
Hi,
I have the following code, where I fill a 3D matrix with data from a struct, which has tables inside. The goal is to concatenate several 3D matrix. However, they have dfferent number of columns, so I don't think I can concatenate them all directly and skip the code below. The code below is taking me really a long time to compute, like days. My question is: how can I modify my code to make it run faster? I know I can preallocate B as B=zeros(50,10000,30), but I would like to know if there any other options. Thank you.
ntables=50
nlines=10000
ncolumns=30
for i=1:1:ntables
for j=1:1:nlines
for k=1:1:ncolumns
B(i,j,k)=table2array(A((i)).data.A_data(j,k))
end
end
end

Accepted Answer

Jan
Jan on 15 Feb 2022
Edited: Jan on 24 Feb 2022
Of course you have to pre-allocate.
ntables = 50;
nlines = 10000;
ncolumns = 30;
B = zeros(ntables, nlines, ncolumns);
for i = 1:ntables
B(i, :, :) = table2array(A(i).data.A_data(:, 1:ncolumns));
end

More Answers (0)

Categories

Find more on Introduction to Installation and Licensing in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!