Vectorizing Value Assignment to an Array of Structures

Posted on Nov 7, 2015

MATLAB code:
% create an array of 100 structures
chan = struct('Index', num2cell(1:100));

% assign new numbers (larger by 3) to the Index field without using a loop

% Method 1
chan = arrayfun(@(s) setfield(s,'Index', s.Index + 3), chan);

% Method 2: This is faster than Method 1, but requires a temporary variable.
new_index = num2cell([chan.Index] + 3);
[chan.Index] = new_index{:};

% Method 3: Surprisingly using a loop is the fastest!!!
for m=1:100, chan(m).Index = chan(m).Index + 3; end

% The fastest time out of 10 runs on my desktop with R2015b
% Method 1: Elapsed time is 0.002056 seconds.
% Method 2: Elapsed time is 0.000357 seconds.
% Method 3: Elapsed time is 0.000124 seconds.