Reshaping a matrix with different column sizes to a vector
12 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Maryam Mohammadipour
am 18 Feb. 2015
Kommentiert: Maryam Mohammadipour
am 18 Feb. 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 Kommentare
Akzeptierte Antwort
Stephen23
am 18 Feb. 2015
Bearbeitet: Stephen23
am 18 Feb. 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]
Weitere Antworten (1)
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!