Reshaping a matrix with different column sizes to a vector
12 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Maryam Mohammadipour
le 18 Fév 2015
Commenté : Maryam Mohammadipour
le 18 Fév 2015
Hello,
Suppose you have a matrix that the number of columns for each row is different (the matrix is 100*132 but not every row has 132 data. Row 1 only has 21 columns and the rest is zero. Row 2 has 23 columns and the rest is zero and so on.
I want to reshape this matrix into a vector in which all of the rows of the original matrix are attached but I don't want the zeros. This is because I want to calculate the median of all elements and if I have the zeros, this will change the result.
For example, assume that the original matrix is:
M = [ 2 3 4 0 0 0; 1 3 6 2 1 0; 1 2 2 1 0 0 ]
and I want to reshape the above matrix to a vector like this:
A = [ 2 3 4 1 3 6 2 1 1 2 2 1 ]
that includes all numbers and excludes zeros.
I know the number of nonzero values in each row. They are available in an array like: Num = [3; 5; 4]
I tried this command but it did not work: reshape( M(:,1:Num(:,1)) , 1 , [])
It only considers the first value in Num and returns this vector instead:
[ 2 3 4 1 3 6 1 2 2 ]
Thank you for your help.
0 commentaires
Réponse acceptée
Stephen23
le 18 Fév 2015
Modifié(e) : Stephen23
le 18 Fév 2015
This code will concatenate exactly the number of values from each row, as given in Num, regardless of the values in the row:
M = [2 3 4 0 0 0; 1 3 6 2 1 0; 1 2 2 1 0 0];
Num = [3; 5; 4];
N = num2cell(M,2);
N = cellfun(@(v,n)v(1:n), N, num2cell(Num(:)), 'UniformOutput',false);
N = [N{:}];
For example if we change values at position Num in each row to zero:
M = [2 3 0 0 0 0; 1 3 6 2 0 0; 1 2 2 0 0 0 ];
then we correctly get
N = [2 3 0 1 3 6 2 0 1 2 2 0]
Plus de réponses (1)
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices 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!