如何从标签向量生成标签矩阵? [英] How to generate label matrix from a label vector?
本文介绍了如何从标签向量生成标签矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的标签向量如下:
y=[3 1 5 3 4 2];
是否有任何有效的方法来生成以下标签矩阵?
Is there any efficient way to generate the following label matrix?
[0 0 1 0 0;
1 0 0 0 0;
0 0 0 0 1;
0 0 1 0 0;
0 0 0 1 0;
0 1 0 0 0;]
更新: 这篇文章和这篇文章都是很好的答案.使用@Nras提供的脚本,以下操作可以处理丢失的标签:
UPDATED: This post and this post are both good answers. Using the scripts provided by @Nras, the following is to handle the missing labels:
Y=[3 1 5 3 4 2];
labels=unique(Y);
[~,indexes]=ismember(Y,labels);
rows = 1:length(Y); %// row indx
T = zeros(length(Y),length(unique(indexes))); %// A matrix full of zeros
T(sub2ind(size(T),rows ,indexes)) = 1; %// Ones at the desired row/column combinations
推荐答案
使用sub2ind
解决此问题.您的y
确定要使用的列,
行总是总是简单地增加1.通过使用sub2ind
,所需的行-列组合将转换为线性索引,然后可以通过矢量化的方式进行处理.
Use sub2ind
for this problem. Your y
determines the columns to use,
the rows are simply always incremented by 1. By using sub2ind
the desired row-column-combinations get transformed to a linear index and can then all be adressed in a vectorized way.
y = [3 1 5 3 4 2]; %// column indx
rows = 1:length(y); %// row indx
M = zeros(length(y), max(y)); %// A matrix full of zeros
M(sub2ind(size(M),rows ,y)) = 1; %// Ones at the desired row/column combinations
这篇关于如何从标签向量生成标签矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文