Effacer les filtres
Effacer les filtres

How to normalize all the matrices in a loop so that each row sums up to 1

12 vues (au cours des 30 derniers jours)
N = 4
n = 2
A = cell(1,N);
for i = 1:N
A{i} = rand(n,n)
end
celldisp(A)
From above command I will get 4 matrices.How to normalize all the matrices( ie all 4 matrices) so that each row sums up to 1.
Thanks

Réponse acceptée

harsha001
harsha001 le 20 Mar 2019
Modifié(e) : harsha001 le 20 Mar 2019
There are two parts to your question - (a) how to normalise each row of a matrix at once, and (b) how to do it independently for each matrix in a cell array.
(a)
use the dot notation to divide each row by the sum of that row
So for a matrix M,
M = M./sum(M,2); % sum acros the 2nd dimension (column) and do a row-wise division
will normalise each row to sum to 1.
If instead you want to normalise each column, simply:
M = M./sum(M,1);
(b) You can either use a for loop to do the same for each matrix A{jj} of the cell array
for jj=1:N
A{jj} = A{jj}./sum(A{jj},2);
end
OR use a neat arrayfun to do the same:
A = arrayfun( @(jj) A{jj}./sum(A{jj},2), 1:N , 'UniformOutput', false );
where i use the array fun to loop over 1 to N, setting uniform output to false so my result is also a cell-array. Imagine it like:
output = arrayfun( @jj, func(something), loop over 1 to N, 'UniformOutput', false)
  2 commentaires
madhan ravi
madhan ravi le 20 Mar 2019
@Harsha: How did you know there is two parts to the question?

Connectez-vous pour commenter.

Plus de réponses (2)

Steven Lord
Steven Lord le 20 Mar 2019
The sum of the absolute values of the elements of a vector is the 1-norm. You can use the normalize function introduced in release R2018a to normalize each row of a matrix by the 1-norm.
A = rand(6);
B = normalize(A, 2, 'norm', 1);
shouldBeCloseTo1 = sum(B, 2)
You can use a for loop or arrayfun to apply normalize to each matrix in the cell array.

Moritz Hesse
Moritz Hesse le 20 Mar 2019
Modifié(e) : Moritz Hesse le 20 Mar 2019
If you have the deep learning toolbox installed, you can use normr to normalise matrix rows. You can access cell contents with curly brace notation
N = 4
n = 2
A = cell(1,N);
for i = 1:N
A{i} = rand(n,n)
end
celldisp(A)
% Loop through cells and normalise matrix rows
for i = 1:N
A{i} = normr(A{i})
end
  2 commentaires
parag gupta
parag gupta le 20 Mar 2019
'normr' requires Deep Learning Toolbox.
Error in Untitledhhho (line 15)
A{i} = normr(A{i})
got this error

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by