将向量转换成逻辑矩阵? [英] Convert vector into logical matrix?
本文介绍了将向量转换成逻辑矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个长度为n的向量y. y(i)是1..m中的整数.有没有一种简单的方法可以将y转换为n x m逻辑矩阵yy,如果y(i)= j,则yy(i,j)= 1,否则为0?这是我一直在做的事情:
I have a vector y of length n. y(i) is an integer in 1..m. Is there a simpler way to convert y into an n x m logical matrix yy, where yy(i, j) = 1 if y(i) = j, but 0 otherwise? Here's how I've been doing it:
% If m is known (m = 3 here), you could write it out all at once
yy = [y == 1; y== 2; y == 3];
yy = reshape(yy, n, 3);
或
% if m is not known ahead of time
yy = [ y == 1 ];
for i = 2:m;
yy = [ yy; y == i ];
end
yy = reshape(yy, n, m);
推荐答案
您可以使用 bsxfun 为此
yy = bsxfun(@eq,y(:),[1,2,3])
y
被转换(如有必要)为列向量,而另一个向量为行向量. bsxfun
隐式扩展m-by-1和1-by-n数组,使结果变为m-by-n.
y
is transformed (if necessary) to a column-vector, while the other vector is a row vector. bsxfun
implicitly expands the m-by-1 and 1-by-n arrays so that the result becomes m-by-n.
这篇关于将向量转换成逻辑矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文