フィルターのクリア

Not sure how to ask this, but here's my scenario:

1 回表示 (過去 30 日間)
Walter
Walter 2016 年 8 月 5 日
コメント済み: Image Analyst 2016 年 8 月 5 日
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?

採用された回答

Sean de Wolski
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 件のコメント
Walter
Walter 2016 年 8 月 5 日
Ahh! accumarray is the trick.. I knew I didn't need to loop over these.. thx!
Image Analyst
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
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

Azzi Abdelmalek
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

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by