How to rearrange values in a matrix

2 ビュー (過去 30 日間)
afrya
afrya 2013 年 11 月 4 日
コメント済み: afrya 2014 年 4 月 6 日
Hello, I have a large matrix with 3 columns(x,y,and z) and I want to rearrange the values inside this matrix. Example:
*Initial matrix
x y z
1 1 5
1 2 6
1 3 7
2 1 8
2 2 9
2 3 2
*Final matrix My goal is to rearrange the values of the matrix in this form
y
x 1 2 3
1 5 6 7 <-z values
2 8 9 2

採用された回答

Sean de Wolski
Sean de Wolski 2013 年 11 月 4 日
There are a few elegant ways to do this. I would use accumarray
data = [
1 1 5
1 2 6
1 3 7
2 1 8
2 2 9
2 3 2];
V = accumarray(data(:,[1 2]),data(:,3))
Now V does not have the index values, but you already know them:
rr = 1:size(V,1) %row
cc = 1:size(V,2) %column
So I would just keep them separate.
  5 件のコメント
afrya
afrya 2013 年 11 月 4 日
When I'm working with decimal numbers,I have the following error
x =
0.6000 0.6000 5.0000
0.6000 0.8000 6.0000
0.6000 0.9000 7.0000
0.8000 0.6000 8.0000
0.8000 0.8000 9.0000
0.8000 0.9000 2.0000
>> V = accumarray(x(:,[1 2]),x(:,3)) Error using accumarray First input SUBS must contain positive integer subscripts.
Do you know how to solve this problem?
Andrei Bobrov
Andrei Bobrov 2013 年 11 月 4 日
see my answer

サインインしてコメントする。

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2013 年 11 月 4 日
編集済み: Andrei Bobrov 2013 年 11 月 4 日
xyz = [1 1 5
1 2 6
1 3 7
2 1 8
2 2 9
2 3 2];
out = nan(max(xyz(:,1:2))+1);
out(2:end,1) = unique(xyz(:,1));
out(1,2:end) = unique(xyz(:,2));
out(2:end,2:end) = accumarray(xyz(:,1:2),xyz(:,3));
ADD
x =[ 0.6000 0.6000 5.0000
0.6000 0.8000 6.0000
0.6000 0.9000 7.0000
0.8000 0.6000 8.0000
0.8000 0.8000 9.0000
0.8000 0.9000 2.0000];
[r,ii,ii] = unique(x(:,1));
[c,jj,jj] = unique(x(:,2));
v = accumarray([ii,jj],x(:,3));
out = [nan,c';r,v];
  6 件のコメント
Andrei Bobrov
Andrei Bobrov 2014 年 4 月 5 日
another variant of last row
out = [nan,rc{2}',nan;rc{1},v,accumarray(c1{1},x(:,3),[],@mean)];
afrya
afrya 2014 年 4 月 6 日
Thanks for your help, it works now

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by