Not sure how to ask this, but here's my scenario:
1 回表示 (過去 30 日間)
古いコメントを表示
Ok, i'm not sure what this transformation is called, but here's what i want to do.
Given a matrix of categorical variables:
x = ['a', 'b';
'a', 'c';
'a', 'b';
'b', 'c';
'c', 'a';
'a', 'd' ]
Generate a matrix that has all of the combination counts:
a b c d
- - - -
a | 0 2 1 1
b | 0 0 1 0
c | 1 0 0 0
d | 0 0 0 0
Any thoughts?
0 件のコメント
採用された回答
Sean de Wolski
2016 年 8 月 5 日
%%Data
x = {'a', 'b';
'a', 'c';
'a', 'b';
'b', 'c';
'c', 'a';
'a', 'd'};
%%Engine
uv = unique(x(:));
[~,idx] = ismember(x,uv);
m = accumarray(idx,1,numel(uv)+[0 0]);
%%Formatting
T = array2table(m,'VariableNames',uv,'RowNames',uv)
Results:
T =
a b c d
_ _ _ _
a 0 2 1 1
b 0 0 1 0
c 1 0 0 0
d 0 0 0 0
2 件のコメント
Image Analyst
2016 年 8 月 5 日
Be sure you comment it well, because, though it's 2 lines shorter than the for loop solution, it's much more cryptic and will be harder for others who maintain or look at your code later to understand what it's doing without comments.
その他の回答 (2 件)
Image Analyst
2016 年 8 月 5 日
A simple, easy to understand for loop works fine:
x = ['a', 'b';
'a', 'c';
'a', 'b';
'b', 'c';
'c', 'a';
'a', 'd' ]
% Make a matrix for all possible 26 letters a-z,
% (or however many you might have);
matrix = zeros(26);
for row = 1 : size(x, 1)
thisRow = x(row, 1) - 'a' + 1;
thisCol = x(row, 2) - 'a' + 1;
matrix(thisRow, thisCol) = matrix(thisRow, thisCol) + 1;
end
% Display in command window:
matrix
0 件のコメント
Azzi Abdelmalek
2016 年 8 月 5 日
編集済み: Azzi Abdelmalek
2016 年 8 月 5 日
x = {'a', 'b'
'a', 'c'
'a', 'b'
'b', 'c'
'c', 'a'
'a', 'd'}
v=regexp('a':'d','\S','match')
[~,jj]=ismember(x,v)
[xx,yy]=ndgrid(1:4,1:4)
freq=zeros(size(xx));
for k=1:numel(xx)
freq(k)=sum(ismember(jj,[xx(k) yy(k)],'rows'));
end
freq
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Resizing and Reshaping Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!