Reputation: 97
I have a matrix (population
, with 8 columns and 100 rows) of positive and negative numbers.
I want to create a matrix where each row has 8 real numbers which satisfy:
I wrote the code below. I tried to normalize the number in the rows but it doesn't work because the result contains negative numbers.
population(:,1:8) = bsxfun(@rdivide,population(:,1:8).',sum(population(:,1:8).')).';
How can I fix this?
For example, the input [1 -2 3]
should give the output [0.375 0 0.625]
Upvotes: 0
Views: 1671
Reputation: 18838
you can do it likes the following:
col_size = size(matrix,2);
matrix = matrix - repmat(min(matrix.').', 1, col_size); % minus minimum
normal_matrix = matrix./repmat(sum(matrix, 2), 1, col_size);
using sum(matrix, 2)
to get sum of rows. Then apply repmat
to repeat this columnar matrix to get a matrix with size of the original matrix. Then divide the original matrix with the repeated columnar matrix.
Upvotes: 0
Reputation: 30047
You simply need to subtract the row-wise minimum (regardless whether it's negative) and divide by the row-wise sum. You can use the dim
argument of min
and sum
to specify the value should be taken row-wise...
% Get positive values by subtractive the row-wise minimum
pos = bsxfun(@minus, data, min(data, [], 2));
% Normalise by dividing by the row-wise sum
normalized = bsxfun(@rdivide, pos, sum(pos,2));
For example:
data = [5 6 0
6 3 2
-1 -2 6];
pos = bsxfun(@minus, data, min(data, [], 2))
>> pos =
[5 6 0
4 1 0
1 0 8]
normalized = bsxfun(@rdivide, pos, sum(pos,2))
>> normalized =
[0.4545 0.5455 0
0.8000 0.2000 0
0.1111 0 0.8889]
Note: from MATLAB 2016b, the new implicit expansion methods mean you don't need bsxfun
, and can simply do
pos = data - min(data, [], 2);
normalized = pos ./ sum(pos, 2);
Upvotes: 1