필터 지우기
필터 지우기

How to reshape matrix by column number?

조회 수: 2 (최근 30일)
Emma Kuttler
Emma Kuttler 2022년 4월 19일
편집: Stephen23 2022년 4월 19일
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]

답변 (2개)

Stephen23
Stephen23 2022년 4월 19일
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
Emma Kuttler
Emma Kuttler 2022년 4월 19일
Thanks! How would you modify the code if you wanted to also return the rows with zero in them?
Stephen23
Stephen23 2022년 4월 19일
편집: Stephen23 2022년 4월 19일
"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

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


KSSV
KSSV 2022년 4월 19일
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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by