创建指标矩阵 [英] Creating Indicator Matrix

查看:41
本文介绍了创建指标矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于大小为 nx 1 的向量 V,我想创建大小为 nx Max 的二进制指示矩阵 M(V)使得M的行条目在对应的列索引中有1,否则0.

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.

例如:如果 V

V = [ 3
      2
      1
      4]

指标矩阵应该是

M= [ 0 0 1 0
     0 1 0 0
     1 0 0 0
     0 0 0 1]

推荐答案

关于像这样的指标矩阵的事情,如果你让它变得稀疏会更好.无论如何,您几乎总是会用它进行矩阵乘法,因此要使乘法成为有效的乘法.

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.

n = 4;
V = [3;2;1;4];
M = sparse(V,1:n,1,n,n);
M =
   (3,1)        1
   (2,2)        1
   (1,3)        1
   (4,4)        1

如果你坚持 M 是一个满矩阵,那么通过使用 full 来实现它是很简单的.

If you insist on M being a full matrix, then making it so is simple after the fact, by use of full.

full(M)
ans =
     0     0     1     0
     0     1     0     0
     1     0     0     0
     0     0     0     1

了解如何使用稀疏矩阵.这样做你会受益匪浅.诚然,对于 4x4 矩阵,稀疏不会有太大的好处.但是示例案例从来都不是您真正的问题.假设 n 真的是 2000?

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?

n = 2000;
V = randperm(n);
M = sparse(V,1:n,1,n,n);
FM = full(M);

whos FM M
  Name         Size                 Bytes  Class     Attributes

  FM        2000x2000            32000000  double              
  M         2000x2000               48008  double    sparse    

稀疏矩阵不仅仅在使用的内存方面有所增加.比较单个矩阵乘法所需的时间.

Sparse matrices do not gain only in terms of memory used. Compare the time required for a single matrix multiply.

A = magic(2000);

tic,B = A*M;toc
Elapsed time is 0.012803 seconds.

tic,B = A*FM;toc
Elapsed time is 0.560671 seconds.

这篇关于创建指标矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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