What is the best way to multiply integer-valued matrices in MATLAB?
I was surprised to learn that the following isn't accepted behavior:
>> x = int64([1, 2])
>> x * x'
Error using *
MTIMES is not fully supported for integer classes. At least one input must be scalar.
To compute elementwise TIMES, use TIMES (.*) instead.
I can always convert to double and back again. Is this the best solution? I'm using R2013b.
C = A . * B multiplies arrays A and B by multiplying corresponding elements. The sizes of A and B must be the same or be compatible. If the sizes of A and B are compatible, then the two arrays implicitly expand to match each other.
Multiply Two Vectors A = [1 1 0 0]; B = [1; 2; 3; 4]; Multiply A times B . The result is a 1-by-1 scalar, also called the dot product or inner product of the vectors A and B . Alternatively, you can calculate the dot product A ⋅ B with the syntax dot(A,B) .
In this simple case, you could get by with using
sum(x.*x)
It seems times
(.*
) is supported properly for integer matrices, although mtimes
( *
) is not.
For general matrix multiplication: let A
and B
be two matrices with suitable sizes so that A*B
exists. Since times
and sum
are supported for integers, you can generalize the above trick, usingbsxfun
and sum
to compute all entries of the product matrix as follows.
Edit: As noted by @July, you need the 'native'
flag in sum
in order to keep the result of integer type. Thanks also for pointing out a problem that was caused by squeeze
, now corrected by using a second permute
.
permute(sum(bsxfun(@times, A.', permute(B, [1 3 2])), 1, 'native'), [2 3 1])
For example:
>> A = int64([1 2; 3 4])
A =
1 2
3 4
>> B = int64([5 7 9; 6 8 10])
B =
5 7 9
6 8 10
>> permute(sum(bsxfun(@times, A.', permute(B, [1 3 2])), 'native'), [2 3 1])
ans =
17 23 29
39 53 67
Anyway, the fastest alternative seems to be double(A)*double(B)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With