How to reshape matrix by column number?
조회 수: 2 (최근 30일)
이전 댓글 표시
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]
댓글 수: 0
답변 (2개)
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]
M = D(:,3:end).';
[C,R] = find(M);
Z = [D(R,1:2),C,nonzeros(M)]
댓글 수: 2
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]
M = D(:,3:end).';
S = size(M);
[C,R] = ndgrid(1:S(1),1:S(2));
Z = [D(R,1:2),C(:),M(:)]
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!