Reshaping a matrix with different column sizes to a vector

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 日

0 投票

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 日

0 投票

Maryam, how about
A = M';
A(A==0) = []

3 件のコメント

Maryam Mohammadipour
Maryam Mohammadipour 2015 年 2 月 18 日
Thanks for this. I think I still need to use reshape. M is a 3*6 matrix. Am I right?
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?

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by