I have an mxn
matrix A, with very small or very large elements. For example:
A = -1e4*randn(10,20);
I would like to create a new matrix C of the same size, as follows:
First, define a matrix B whose elements are the exponential of the elements of A:
B = exp(A)
Then, the matrix C is defined such that each column of C is proportional to the corresponding column of B and the sum of each column of C is equal to 1. In other words, if we take an element of B and divide it by the sum of all the elements of the same columns, then we obtain the corresponding element of C:
C = bsxfun(@rdivide,B,sum(B));
Mathematically:
Clearly, all the elements of C are between 0 and 1. However, when computing using the following code, the obtained matrix contains many NaNs:
A = -1e4*randn(10,20);
B = exp(A);
C = bsxfun(@rdivide,B,sum(B));
sum(sum(isnan(ee)))
I hope somebody can suggest a way to overcome this issue. Thank you very much in advance.
Update: Please note that the goal is the matrix C. I defined the matrix B just for explanation purpose, and we may not have to compute it. (We shouldn't actually. As @EJG89 pointed out that B contains only Inf and 0).
Update 2: Thanks to @EJG89 for the link to the Log Sum of Exponentials technique, which might be useful. I'm working on finding similar analytical tricks for my problem.
Update 3: As suggested by @Dan and @EJG89, we can subtract each column with a constant to obtain a new matrix within a reasonable range. Clearly, we have
for any constant C. We can choose C as the maximum value of each column:
(a_{max,j} is the maximum of the j-th column), then
I feel that this choice might give a very good approximation, but I don't know how good it is :|
The new code is:
A = bsxfun(@minus,A,max(A));
B = exp(A);
C = bsxfun(@rdivide,B,sum(B));