假设我有以下矩阵,
1 2 3 4 5 6 7 8
2 3 4 5 6 7 8 1
3 4 5 6 7 8 1 2
4 5 6 7 8 1 2 3
1 8 7 6 5 4 3 2
2 7 6 5 4 3 2 9
3 6 5 4 3 2 9 8
4 5 4 3 2 9 8 7
我想创建一个包含 4 个矩阵的数组,根据第 1 列进行分类。
例如,输出应如下所示,
[
2 3 4 5 6 7 8
8 7 6 5 4 3 2
3 4 5 6 7 8 1
7 6 5 4 3 2 9
4 5 6 7 8 1 2
6 5 4 3 2 9 8
5 6 7 8 1 2 3
5 4 3 2 9 8 7
]
我的目标是申请this Parzen function给他们每个人。
<小时/>是不是像下面这样?
function [retval] = bayes (train, test)
classCounts = rows(unique(train(:,1)));
pdfmx = ones(rows(test), classCounts);
variance = 0.25;
pdf = parzen(train(:,2:end), test(:,2:end), variance);
for cl=1:classCounts
clidx = train(:,1) == cl;
mu(:,cl) = train(clidx,2:end);
end
retval = mu;
endfunction
此代码生成以下错误,
>> bayes(mat, mat)
error: bayes: A(I,J,...) = X: dimensions mismatch
error: called from
bayes at line 11 column 12
>>
最佳答案
这是 accumarray
的经典工作。它输出一个元胞数组,但我建议您继续使用 3D 矩阵。
%// data
A = [1 2 3 4 5 6 7 8
2 3 4 5 6 7 8 1
3 4 5 6 7 8 1 2
4 5 6 7 8 1 2 3
1 8 7 6 5 4 3 2
2 7 6 5 4 3 2 9
3 6 5 4 3 2 9 8
4 5 4 3 2 9 8 7]
%// input
groupid = A(:,1); %// group identifier
rowidx = 1:size(A,1); %// row index
%// accumarray
cellArray = accumarray(groupid(:),rowidx (:),[],@(x) {A(x,2:end)})
%// transform cell array to 3D-Matrix
threeDArray = cat(3,cellArray{:})
说明
accumarray
是什么意思? ?
- 它采用
vals = rowidx
的所有元素与相同的subs = groupid
,对其进行分组并执行操作。 - 由于您想要对矩阵的行而不是单个向量执行操作,但需要向量输入,因此您可以通过实际引入行索引作为输入来“欺骗”accumarray,然后在应用的函数中使用该索引里>
-
A(x,2:end)
意味着你拿走了所有rowidx
与相同的groupid
存储在x
然后你用它来访问你的矩阵A
,你输入{}
周围获得元胞数组输出
cellArray{1} =
8 7 6 5 4 3 2
2 3 4 5 6 7 8
cellArray{2} =
7 6 5 4 3 2 9
3 4 5 6 7 8 1
cellArray{3} =
6 5 4 3 2 9 8
4 5 6 7 8 1 2
cellArray{4} =
5 4 3 2 9 8 7
5 6 7 8 1 2 3
<小时/>
threeDArray(:,:,1) =
8 7 6 5 4 3 2
2 3 4 5 6 7 8
threeDArray(:,:,2) =
7 6 5 4 3 2 9
3 4 5 6 7 8 1
threeDArray(:,:,3) =
6 5 4 3 2 9 8
4 5 6 7 8 1 2
threeDArray(:,:,4) =
5 4 3 2 9 8 7
5 6 7 8 1 2 3
<小时/>
如果输出中的行顺序很重要,则需要 accumarray
的“稳定版本” (灵感来自this answer:
%// stabilize accumarray
sz = max(groupid,[],1);
[~, I] = sort(groupid*cumprod([1,sz(1:end-1)]).');
%// stable accumarray
cellArray = accumarray(groupid(I,:),rowidx(I),[],@(x) {A(x,2:end)})
<小时/>
cellArray{1} =
2 3 4 5 6 7 8
8 7 6 5 4 3 2
cellArray{2} =
3 4 5 6 7 8 1
7 6 5 4 3 2 9
cellArray{3} =
4 5 6 7 8 1 2
6 5 4 3 2 9 8
cellArray{4} =
5 6 7 8 1 2 3
5 4 3 2 9 8 7
<小时/>
threeDArray(:,:,1) =
2 3 4 5 6 7 8
8 7 6 5 4 3 2
threeDArray(:,:,2) =
3 4 5 6 7 8 1
7 6 5 4 3 2 9
threeDArray(:,:,3) =
4 5 6 7 8 1 2
6 5 4 3 2 9 8
threeDArray(:,:,4) =
5 6 7 8 1 2 3
5 4 3 2 9 8 7
关于matlab - 如何使用第一列作为索引从单个矩阵创建矩阵数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40445388/