将向量转换为逻辑矩阵?
我有一个长度为 n 的向量 y 。 y(i) 是 1..m 范围内的整数。是否有更简单的方法将 y 转换为 nxm 逻辑矩阵 yy,其中如果 y(i) = j,则 yy(i, j) = 1,否则为 0?这就是我一直在做的事情:
% 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);
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);
or
% 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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用 bsxfun 来
转换此
y
(如有必要)为列向量,而另一个向量是行向量。bsxfun
隐式扩展 m×1 和 1×n 数组,使结果变为 m×n。You can use bsxfun for this
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.如果 n*m 足够大(并且 m 本身足够大),则最好将 yy 创建为稀疏矩阵。您的 y 向量实际上是一种特殊类型的稀疏矩阵格式,但我们可以通过执行以下操作将其转换为内置稀疏矩阵格式。
这将使您的存储空间保持为 O(n)。如果您使用 yy 进行大量索引,它不会给您带来很多好处。如果是这种情况,您最好使用原始稀疏结构(即
y
)。If n*m is sufficiently large (and m is, by itself, sufficiently large), it is a good idea to create
yy
as a sparse matrix. Youry
vector is really a special type of sparse matrix format, but we can translate it into the built-in sparse matrix format by doing the following.This will keep your storage to O(n). It is not going to be doing you a lot of favors if you are using
yy
for a lot of indexing. If that is the case you are better off using your original sparse structure (i.e.,y
).对您的方法稍作修改:
A slight modification to your method:
来自 Coursera 上的机器学习:
这要求列表是一个范围
1:m
(如 OP 所述)。对于不规则列表,例如[2 3 5]
,请执行以下操作 注意:未在 MATLAB 上进行测试。
From Machine Learning on Coursera:
This requires that the list be a range
1:m
(as OP stated). For an irregular list, like[2 3 5]
, do thisNote: not tested on MATLAB.
在八度中你可以写:
In octave you can write: