How to reshape matrix by column number?
1 回表示 (過去 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 で Matrices and Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!