
258 Accelerating MATLAB
®
Performance
In the fourth alternative, we use matrix multiplication to obtain the array indices in
order to do everything in a single line of code:
A([1:size(A,1)]' * ones(1,2),
[1:size(A,2)]' * ones(1,3))
5.4.1 A Simple Example
Consider the following problem: we have a numeric matrix A and wish to normalize each
row independently, so that each row sums to 1. We can loop over all data rows, sum the
values in each row, and then divide each element in that row with its total:
A = rand(1e6,3); % 1Mx3 test data
% loop over all rows
for row = 1 : size(A, 1)
% sum all elements in the "i"th row
total = 0;
for col ...