注册 | 登录

解决How to convert logical sparse matrix into integer sparse matrix in MATLAB?

itPublisher 分享于



推荐:matlab-sparse函数和full函数-sparse matrix和full matrix

sparse函数 功能:Create sparse matrix-创建稀疏矩阵 用法1:S=sparse(X)——将矩阵X转化为稀疏矩阵的形式,即矩阵X中任何零元素去除,非零元素及其下标(索引

I have a matrix I want to consider it as adjacency matrix of corresponding graph, so I'm replacing every non zero element with 1:

A = A ~- 0

Now I want to calculate A*A but I can't because

>> A*A    
Error using *
Both logical inputs must be scalar.
To compute elementwise TIMES, use TIMES (.*) instead

and I for some reason I cannot just convert logical matrix to integer

>> uint(A)
Error using numerictype (line 172)
Invalid arguments (WordLength must be a scalar numeric value).

Error in fixdt (line 186)
        embeddedType = numerictype( varargin{:} );

Error in uint (line 14)
DataType = fixdt(0,WordLength,0);

I could do it by converting matrix to full rank back and forth but this is impractical for my task.

matlab matrix sparse-matrix
  this question
asked Jan 28 '14 at 1:40 Moonwalker 796 15 36


1 Answers


Firstly, you would want to be using uint8 or similar, as opposed to uint - read the help files as to what the difference is, uint doesn't do what you think it does. However, according to this forum post, the only valid sparse data types are double or logical. You've got a logical matrix, but it would appear that sparse matrix multiplication is not defined for logical matrices. Thus, you must convert A to double form before you will be able to multiply it as you are trying to.

推荐:Leetcode: Sparse Matrix Multiplication

Question Given two sparse matrices A and B, return the result of AB. You may assume that A’s column number is equal to B’s row number. Example: A =

Alternatively, use A^2 instead - this will work with logical sparse matrices. Don't know why it's different.

  this answer
answered Jan 28 '14 at 1:48 MrAzzaman 3,619 5 20      Thank you for the response. A^2 looks strange indeed, it would be interesting to see why it works... –  Moonwalker Jan 28 '14 at 1:51 1   @Moonwalker: the result of A^2 is a double so mpower likely converts A beforehand (and the result can thus be greater than one of course). Not sure why mtimes doesn't do the same. –  horchler Jan 28 '14 at 19:34


推荐:Sparse Matrix, MUMPS

Intersystems Cache' = multidimensional Sparse Matrix, MUMPS Caché 非常适合Partners关键任务软件








您的注册邮箱: 修改

重新发送激活邮件 进入我的邮箱