How to reshape matrix by column number?

1 回表示 (過去 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 Center および File ExchangeMatrices and Arrays についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by