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

itPublisher 分享于

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

I have a matrix https://www.cise.ufl.edu/research/sparse/matrices/Hamm/add20.html 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

|

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.

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.

|
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

|

×
• 登录
• 注册

×