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

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

问题描述

有关尺寸 NX最大的一个vector V 大小的 NX 1 ,我想创建二进制指示器矩阵的 M (V)这样的行项的 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]


解决方案

关于这样一个指标矩阵的事情,就是它是更好,如果你让它稀疏。你几乎总是乘用也无妨做一个矩阵,这样使该乘一个有效率的。

  N = 4;
V = [3; 2; 1; 4〕;
M =稀疏(V,1:N,1,N,N);
M =
   (3,1)1
   (2,2)1
   (1,3)1
   (4,4)1

如果你坚持M是一个完整的矩阵,使其成为这样的事实经过简单的,利用的全部。

 满(M)
ANS =
     0 0 1 0
     0 1 0 0
     1 0 0 0
     0 0 0 1

了解如何使用稀疏矩阵。你会这样做大大获益。诚然,对于一个4x4矩阵,稀疏不会受到太大收获。但这个例子的情况下绝不是你真正的问题。假设n为真的2000?

  N = 2000;
V = randperm(正);
M =稀疏(V,1:N,1,N,N);
FM =满(M);卫生组织FM中号
  名称大小字节类属性  FM 2000×2000 32000000双
  中号2000×2000 48008双疏

稀疏矩阵不使用内存方面不仅收获。比较为单个矩阵乘法所需的时间。

  A =魔法(2000);抽动,B = A * M; TOC
所用时间是0.012803秒。抽动,B = A * FM; TOC
所用时间是0.560671秒。

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]

解决方案

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

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

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天全站免登陆