Modifying large arrays slower than modifying structure arrays?

4 views (last 30 days)
I'm having issues with my code where I noticed manipulating large matrix arrays is extremely slow.
In my original implementation, I have to read in some data from a binary file using a for loop. I noticed that if I inserted the data into an array of structures instead of putting the data directly into an initialized matrix array, my performance was much better. I'm not sure why this is happening? Could someone provide me with some insight?
Below is a representative example of the performance issues I'm seeing.
% set up raw data
n = 10000;
rawNum = (1:n);
rawData = magic(n); % if n==10000, data is about 0.75 GB
% struct example
simpleStruct.num = [];
simpleStruct.data = [];
S(n,1) = simpleStruct;
tic
for i=1:n
S(i).num = rawNum(i);
S(i).data = rawData(i,:);
end
fprintf("Time took to populate struct array: %1.3f seconds.\n",toc);
% array example
arrayNum = zeros(n,1);
arrayData = zeros(n,n);
tic
for i=1:n
arrayNum(i) = rawNum(i);
arrayData(i,:) = rawData(i,:);
end
fprintf("Time took to populate plain ole array: %1.3f seconds.\n",toc);

Accepted Answer

Walter Roberson
Walter Roberson on 11 Sep 2019
Row versus column ordering effects.
>> tic;for i = 1:n; arrayNum(i) = rawNum(i); arrayData(i,:) = rawData(i,:); end;toc
Elapsed time is 2.254735 seconds.
>> tic;for i = 1:n; arrayNum(i) = rawNum(i); arrayData(:,i) = rawData(:,i); end;toc
Elapsed time is 0.196039 seconds.
  2 Comments
Joshua  Robinson
Joshua Robinson on 11 Sep 2019
Edited: Joshua Robinson on 11 Sep 2019
Thanks!
EDIT: I guess however, if I update my original question to now include the effects of row vectors vs column vectors, it's still true that matlab handles the structs better then either the column vector or row vector.
% set up raw data
n = 10000;
rawNum = (1:n);
rawData = magic(n); % if n==10000, data is about 0.75 GB
% struct example
simpleStruct.num = [];
simpleStruct.data = [];
S(n,1) = simpleStruct;
tic
for i=1:n
S(i).num = rawNum(i);
S(i).data = rawData(:,i);
end
fprintf("Time took to populate struct array: %1.3f seconds.\n",toc);
% array column example
arrayNum = zeros(n,1);
arrayData = zeros(n,n);
tic
for i=1:n
arrayNum(i) = rawNum(i);
arrayData(:,i) = rawData(:,i);
end
fprintf("Time took to populate columns in array: %1.3f seconds.\n",toc);
% array row example
arrayNum = zeros(n,1);
arrayData = zeros(n,n);
tic
for i=1:n
arrayNum(i) = rawNum(i);
arrayData(i,:) = rawData(i,:);
end
fprintf("Time took to populate rows in array: %1.3f seconds.\n",toc);
Time took to populate struct array: 0.387 seconds.
Time took to populate columns in array: 0.534 seconds.
Time took to populate rows in array: 2.307 seconds.

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!