How to reshape matrix by column number?

3 views (last 30 days)
Emma Kuttler
Emma Kuttler on 19 Apr 2022
Edited: Stephen23 on 19 Apr 2022
Hi, I have a 163 x 13 matrix of numerical values that I'd like to turn into a longer matrix. I'd like to keep the first two columns the same, but output the column number in a new column (starting with column 3 assigned the key 1), and then the value for that column in the next column. Then I'd like to remove rows with zero in the fourth column.
For example, if "demand" is my matrix, I want to produce "demandlong"
demand = [1 78 0 0 0 0 0 0 0 0 8 45 0
1 79 0 0 0 0 31 8 0 0 0 0 0
1 80 456 0 4 0 39 0 0 0 16 0 0]
demandlong =
[1 78 10 45
1 79 5 31
1 80 1 456
1 80 3 4
1 80 5 39
1 80 9 16]

Answers (2)

Stephen23
Stephen23 on 19 Apr 2022
D = [1,78,0,0,0,0,0,0,0,0,8,45,0;1,79,0,0,0,0,31,8,0,0,0,0,0;1,80,456,0,4,0,39,0,0,0,16,0,0]
D = 3×13
1 78 0 0 0 0 0 0 0 0 8 45 0 1 79 0 0 0 0 31 8 0 0 0 0 0 1 80 456 0 4 0 39 0 0 0 16 0 0
M = D(:,3:end).';
[C,R] = find(M);
Z = [D(R,1:2),C,nonzeros(M)]
Z = 8×4
1 78 9 8 1 78 10 45 1 79 5 31 1 79 6 8 1 80 1 456 1 80 3 4 1 80 5 39 1 80 9 16
  2 Comments
Emma Kuttler
Emma Kuttler on 19 Apr 2022
Thanks! How would you modify the code if you wanted to also return the rows with zero in them?
Stephen23
Stephen23 on 19 Apr 2022
Edited: Stephen23 on 19 Apr 2022
"How would you modify the code if you wanted to also return the rows with zero in them?"
Do you mean something like this?:
D = [1,78,0,0,0,0,0,0,0,0,8,45,0;1,79,0,0,0,0,31,8,0,0,0,0,0;1,80,456,0,4,0,39,0,0,0,16,0,0]
D = 3×13
1 78 0 0 0 0 0 0 0 0 8 45 0 1 79 0 0 0 0 31 8 0 0 0 0 0 1 80 456 0 4 0 39 0 0 0 16 0 0
M = D(:,3:end).';
S = size(M);
[C,R] = ndgrid(1:S(1),1:S(2));
Z = [D(R,1:2),C(:),M(:)]
Z = 33×4
1 78 1 0 1 78 2 0 1 78 3 0 1 78 4 0 1 78 5 0 1 78 6 0 1 78 7 0 1 78 8 0 1 78 9 8 1 78 10 45

Sign in to comment.


KSSV
KSSV on 19 Apr 2022
demand = [1 78 0 0 0 0 0 0 0 0 8 45 0
1 79 0 0 0 0 31 8 0 0 0 0 0
1 80 456 0 4 0 39 0 0 0 16 0 0] ;
n = size(demand,1) ;
iwant = zeros(n,4) ;
iwant(:,1:2) = demand(:,1:2) ;
for i = 1:n
id = find(demand(i,:)) ;
iwant(i,3) = id(3)-2 ;
iwant(i,4) = demand(i,id(3)) ;
end
iwant
iwant = 3×4
1 78 9 8 1 79 5 31 1 80 1 456

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!