Reshape a matrix according to specific columns.
古いコメントを表示
Hi all,
I have a problem with a specific task I am trying to solve but I am unable to get the correct code to accomplish this in MATLAB.
What I am trying to do is reshape a matrix of 3 columns into a M x N matrix based upon the unique values in the first two columns.
So I in general I have something like this,
[1 a 5;
1 b 6;
1 c 13;
2 a 8;
2 b 9;
3 a 10;
3 b 11;
3 c 12]
And I would like the output to be something like this;
1 2 3
a 5 8 10
b 6 9 11
c 13 NaN 12
I am thinking I should define the size of the matrix dimensions by the output from the unique function applied on the first two columns provides, but after this I am lost on how to proceed.
Thank you in advance for your help.
Willem
採用された回答
その他の回答 (1 件)
Andrei Bobrov
2013 年 8 月 12 日
編集済み: Andrei Bobrov
2013 年 8 月 12 日
A = {1 'a' 5;
1 'b' 6;
1 'c' 13;
2 'a' 8;
2 'b' 9;
3 'a' 10;
3 'b' 11;
3 'c' 12}
[i0,i2,i2] = unique(A(:,2))
c = cat(1,A{:,1}); % OR [j0,j2,j2] = unique(cat(1,A{:,1}));
Z = accumarray([i2,c],cat(1,A{:,3}),[],[],nan);% OR c -> j2
out = cell(size(Z)+1);
out(2:end,1) =i0;
out(2:end,2:end) = num2cell(Z);
out(1,2:end) = num2cell(1:max(c)); % OR num2cell(j0);
5 件のコメント
Azzi Abdelmalek
2013 年 8 月 12 日
This will not work for
A = {1 'a' 5;
1 'b' 6;
1 'c' 13;
2 'a' 8;
2 'b' 9;
5 'a' 10;
5 'b' 11;
5 'c' 12}
Andrei Bobrov
2013 年 8 月 12 日
corrected
Azzi Abdelmalek
2013 年 8 月 12 日
The result is
[] [ 1] [ 2] [ 3] [ 4] [ 5]
'a' [ 5] [ 8] [NaN] [NaN] [10]
'b' [ 6] [ 9] [NaN] [NaN] [11]
'c' [13] [NaN] [NaN] [NaN] [12]
It should be
[] [ 1] [ 2] [ 5]
'a' [ 5] [ 8] [10]
'b' [ 6] [ 9] [11]
'c' [13] [NaN] [12]
Azzi Abdelmalek
2013 年 8 月 12 日
You can add
idx1=setdiff(min(c):max(c),c);
out(:,idx1+1)=[]
Andrei Bobrov
2013 年 8 月 12 日
編集済み: Andrei Bobrov
2013 年 8 月 12 日
used expression after sign '% OR'
カテゴリ
ヘルプ センター および File Exchange で Data Preprocessing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!