Reshaping a matrix with different column sizes to a vector
Show older comments
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.
Accepted Answer
More Answers (1)
Mischa Kim
on 18 Feb 2015
Maryam, how about
A = M';
A(A==0) = []
3 Comments
Maryam Mohammadipour
on 18 Feb 2015
Mischa Kim
on 18 Feb 2015
Nope. This works as is. Just give it a try.
Maryam Mohammadipour
on 18 Feb 2015
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!