Matlab,整数向量到无循环的二进制矩阵 [英] Matlab, Integer vector to binary matrix without loop

查看:88
本文介绍了Matlab,整数向量到无循环的二进制矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有N个元素的矢量,所有元素均为1-M.我想将其转换为NxM矩阵,每行仅包含零,但将i:th元素设置为1,i是向量中的整数.

I have a vector with N elements, all integers 1-M. I want to convert this to a NxM matrix with each row containing only zeros except for the i:th element set to one, i being the integer in the vector.

例如: [1 1 3] => [1 0 0; 1 0 0; 0 0 1]

For example: [1 1 3] => [1 0 0; 1 0 0; 0 0 1]

我目前是这样循环执行的:

I currently do this in a loop, like this:

y_vec = zeros(m, num_labels);
for i = 1:m
    y_vec(i, y(i)) = 1;
end

有没有办法做到这一点而没有循环?

Is there a way to do this without a loop?

推荐答案

是的,有:

y = [1 1 3];
m = length(y);
num_labels = max(y);

%# initialize y_vec
y_vec = zeros(m,num_labels);

%# create a linear index from {row,y}
idx = sub2ind(size(y_vec),1:m,y);

%# set the proper elements of y_vec to 1
y_vec(idx) = 1;

这篇关于Matlab,整数向量到无循环的二进制矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆