创建指标矩阵
对于大小为 nx 1 的向量 V,我想创建大小为 nx Max(V) 的二元指示矩阵 M 使得M的行条目在相应的列索引中具有1,否则为0。
例如:如果V是
V = [ 3
2
1
4]
指标矩阵应该是
M= [ 0 0 1 0
0 1 0 0
1 0 0 0
0 0 0 1]
For a vector V of size n x 1, I would like to create binary indicator matrix M of the size n x Max(V) such that the row entries of M have 1 in the corresponding columns index, 0 otherwise.
For eg: If V is
V = [ 3
2
1
4]
The indicator matrix should be
M= [ 0 0 1 0
0 1 0 0
1 0 0 0
0 0 0 1]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
像这样的指标矩阵的问题是,如果使它稀疏的话会更好。无论如何,你几乎总是会用它进行矩阵乘法,因此要使该乘法成为有效的乘法。
如果您坚持 M 是一个满矩阵,那么事后通过使用 full 使其变得如此简单。
了解如何使用稀疏矩阵。这样做你将会受益匪浅。诚然,对于 4x4 矩阵,稀疏不会有太大增益。但示例案例从来都不是您真正的问题。假设 n 确实是 2000?
稀疏矩阵不仅仅在内存使用方面有所提高。比较单个矩阵乘法所需的时间。
The thing about an indicator matrix like this, is it is better if you make it sparse. You will almost always be doing a matrix multiply with it anyway, so make that multiply an efficient one.
If you insist on M being a full matrix, then making it so is simple after the fact, by use of full.
Learn how to use sparse matrices. You will gain greatly from doing so. Admittedly, for a 4x4 matrix, sparse will not gain by much. But the example cases are never your true problem. Suppose that n was really 2000?
Sparse matrices do not gain only in terms of memory used. Compare the time required for a single matrix multiply.
执行此操作的快速方法 - 如果您不需要稀疏矩阵 - 是创建一个大小至少为 max(v) 的单位矩阵,然后通过从 v 中提取索引来创建指示矩阵:
a quick way to do this - if you do not require sparse matrix - is to create an identity matrix, of size at least the max(v), then to create your indicator matrix by extracting indexes from v:
为了记忆起见,您希望创建稀疏索引矩阵。这很简单:
我自己用过这个,享受吧:)
You would like to create the Index matrix to be sparse for memory sake. It is as easy as:
I've used this myself, enjoy :)
您只需将
V
中的列索引与行索引组合起来即可创建 线性索引,然后用它来填充M
(初始化为零):You can simply combine the column index in
V
with a row index to create a linear index, then use that to fillM
(initialized to zeroes):这是另一种方法,类似于
sparse
但使用accumarray
:Here's another approach, similar to
sparse
but withaccumarray
:将生成一个稀疏矩阵,您可以将其作为完整版本用于计算。
您可以使用 full(M) 来“膨胀”M 以实际存储零。
will produce a sparse matrix that you can use in calculations as a full version.
You could use full(M) to "inflate" M to actually store zeros.