필터 지우기
필터 지우기

Merge confusion matrices in nice, vectorized way.

조회 수: 5 (최근 30일)
Adriano
Adriano 2011년 8월 23일
Hello everyone,
I have several confusion matrices, which are a 2D cell array. The first row and the first columns are strings. The rest are numbers. Something like this:
MATRIX 1
A B C
A 100 10 15
B 20 150 25
C 10 10 200
MATRIX 2
A B D
A 150 5 10
B 10 100 15
D 15 15 100
MATRIX 3
B E
B 100 15
E 5 150
How can I merge the matrices in a vectorized way so the output is something like this?
DESIRED OUTPUT
A B C D E
A 250 15 15 10 0
B 30 350 25 15 15
C 10 10 200 0 0
D 15 15 0 100 0
E 0 5 0 0 150
Which means merge all the matrices into one, including the labels in the first row and the first column label. Where the rows and columns overlap, add them. I could do this with some loops, but I am interested in the nice, vectorized way :) .

채택된 답변

Oleg Komarov
Oleg Komarov 2011년 8월 23일
m1 = {'' 'A' 'B' 'C'
'A' 100 10 15
'B' 20 150 25
'C' 10 10 200};
m2 = {'' 'A' 'B' 'D'
'A' 150 5 10
'B' 10 100 15
'D' 15 15 100};
m3 = {'' 'B' 'E'
'B' 100 15
'E' 5 150};
m = [unPivot(m1); unPivot(m2); unPivot(m3)];
Pivot(m,@sum,[],0)
ans =
[NaN] 'A' 'B' 'C' 'D' 'E'
'A' [250] [ 15] [ 15] [ 10] [ 0]
'B' [ 30] [350] [ 25] [ 15] [ 15]
'C' [ 10] [ 10] [200] [ 0] [ 0]
'D' [ 15] [ 15] [ 0] [100] [ 0]
'E' [ 0] [ 5] [ 0] [ 0] [150]
One suggestion, using text labels is highly inefficient because the resulting cell array will be very memory demanding. Convert the labels to numbers 1 2 3 ... and you'll see the difference.

추가 답변 (1개)

Kelly Kearney
Kelly Kearney 2011년 8월 23일
You might want to add a loop over the columns if your matrices will be varying sizes, but otherwise...
Your data:
m{1} = {...
'rowA.' 1 2 3
'rowB.' 1 2 3
'rowC.' 1 2 3};
m{2} = {...
'rowA.' 2 3 4
'rowD.' 2 3 4
'rowE.' 2 3 4};
m{3} = {...
'rowD.' 3 4 5
'rowF.' 3 4 5};
Combine matrices into one...
mall = cat(1, m{:});
lbl = mall(:,1);
data = cell2mat(mall(:,2:end));
... and sum by label:
[lbl, blah, idx] = unique(lbl);
data = [accumarray(idx, data(:,1)) ...
accumarray(idx, data(:,2)) ...
accumarray(idx, data(:,3))];
  댓글 수: 2
Kelly Kearney
Kelly Kearney 2011년 8월 23일
Hey, you changed your question and example completely while I was typing my answer!
Adriano
Adriano 2011년 8월 23일
Sorry, my mistake, I hadn't realized the real problem :-(

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by