Reputation: 2050
I want to normalize a matrix per column. I now have this code which works fine:
A = randn(10,3)
maxA = max(A,[],1)
minA = min(A,[],1)
for i=1:size(A,2)
A(:,i) = (A(:,i) - minA(i) ./ (maxA(i) - minA(i))
end
However, since my matrix will be much bigger, about 10k by 60k looping will take forever. How could I vectorize my code?
I have thought of using Matlab's normc
but that does not do the same as my code.
Upvotes: 3
Views: 2462
Reputation: 14108
In general it could be:
A = (A - ones(size(A)) * diag(minA)) / diag(maxA - minA);
or
A = (A - ones(size(A)) * diag(minA)) * diag(1 ./ (maxA - minA));
but taking into account the size:
m = repmat(minA, size(A, 1), 1);
n = repmat(maxA - minA, size(A, 1), 1);
A = (A - m) ./ n;
Upvotes: 0
Reputation: 9317
You can use bsxfun
A = randn(10,3)
maxA = max(A,[],1)
minA = min(A,[],1)
bsxfun(@minus, A, minA ./ abs(maxA - minA))
However, I do not quite understand your normalizing. Wouldn't one rather use
(A(:,i) - minA(i)) ./ (maxA(i) - minA(i))
to normalize? If so, the bsxfun
statement should read:
bsxfun(@times, bsxfun(@minus, A, minA), 1./abs(maxA - minA))
Upvotes: 5