Jeeyoung Kim
Jeeyoung Kim

Reputation: 6098

Row-normalize matrix

Is there any efficient (speed of computation + amount of keystrokes) way to perform row-normalization in MATLAB, using the built in functions?

This is what I've came up with so far

A = rand(m, n); % m rows, n cols
v = pdist2(zeros(1, size(A, 2)), A);
normA = diag(1./v) * A;

Upvotes: 4

Views: 5288

Answers (1)

dantswain
dantswain

Reputation: 5467

Assuming you want row sums to be 1:

bsxfun(@times, A, 1./(sum(A, 2)))

Edit

If you're looking for the l2 norm as @Oli suggests below, then

bsxfun(@times, A, 1./sqrt(sum(A.^2, 2)))

In that case, you can semi-gracefully handle zero row sums by doing

bsxfun(@times, A, 1./(max(sum(A, 2), eps)))

Upvotes: 7

Related Questions