Reshaping a matrix with different column sizes to a vector

12 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

Stephen23
Stephen23 el 18 de Feb. de 2015
Editada: Stephen23 el 18 de Feb. de 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]

Más respuestas (1)

Mischa Kim
Mischa Kim el 18 de Feb. de 2015
Maryam, how about
A = M';
A(A==0) = []
  3 comentarios
Mischa Kim
Mischa Kim el 18 de Feb. de 2015
Nope. This works as is. Just give it a try.
Maryam Mohammadipour
Maryam Mohammadipour el 18 de Feb. de 2015
One other question, what if there are some zeros between the numbers that I want to have them. So only the number that I have in the Num vector tells me how many I want to include?

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by