我目前有一个名为赋值(例如[1, 1, 3, 2]
)的向量,其大小为NUM_PATCHES
。我想创建一个维度feat_vecs
的二维矩阵[NUM_CLUSTERS, NUM_PATCHES]
,以便矩阵看起来像这样:
[1, 1, 0, 0
0, 0, 0, 1
0, 0, 1, 0]
因此,如果我们有assignments(i)
,我希望相应的列i
和行assignments(i)
的值为1
。
我目前正在使用此代码完成此操作:
feat_vecs = full(sparse(assignments, 1:NUM_PATCHES, ones(NUM_PATCHES, 1), NUM_CLUSTERS, NUM_PATCHES));
我也尝试使用此代码使用sub2ind:
feat_vecs = zeros(NUM_CLUSTERS, NUM_PATCHES);
feat_vecs(sub2ind([NUM_CLUSTERS, NUM_PATCHES], assignments, 1:NUM_PATCHES)) = 1;
然而,第二段代码似乎有点慢。
>> tic;
>> feat_vecs = full(sparse(assignments, 1:NUM_PATCHES, ones(NUM_PATCHES, 1), NUM_CLUSTERS, NUM_PATCHES));
>> toc;
Elapsed time is 0.011319 seconds.
>> tic;
>> feat_vecs = zeros(NUM_CLUSTERS, NUM_PATCHES);
>> feat_vecs(sub2ind([NUM_CLUSTERS, NUM_PATCHES], assignments', 1:NUM_PATCHES)) = 1;
>> toc;
Elapsed time is 0.014425 seconds.
我正在运行这段代码数千次,因此运行时的一小部分差异很快就会增加。我想知道是否有更快或更有效的方法来完成这项任务。