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!