Reshaping a matrix with different column sizes to a vector

조회 수: 12 (최근 30일)
Maryam Mohammadipour
Maryam Mohammadipour 2015년 2월 18일
댓글: Maryam Mohammadipour 2015년 2월 18일
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.

채택된 답변

Stephen23
Stephen23 2015년 2월 18일
편집: Stephen23 2015년 2월 18일
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]

추가 답변 (1개)

Mischa Kim
Mischa Kim 2015년 2월 18일
Maryam, how about
A = M';
A(A==0) = []
  댓글 수: 3
Mischa Kim
Mischa Kim 2015년 2월 18일
Nope. This works as is. Just give it a try.
Maryam Mohammadipour
Maryam Mohammadipour 2015년 2월 18일
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?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by