gpt4 book ai didi

matlab - MATLAB 中整数值矩阵的乘法

转载 作者:太空宇宙 更新时间:2023-11-03 19:34:48 25 4
gpt4 key购买 nike

在 MATLAB 中乘以整数值矩阵的最佳方法是什么?

我很惊讶地得知以下行为是 Not Acceptable :

>> 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.

我总是可以转换成 double 并再次转换回来。这是最好的解决方案吗?我正在使用 R2013b。

最佳答案

在这种简单的情况下,您可以使用

sum(x.*x)

似乎 times (.*) 被整数矩阵正确支持,尽管 mtimes ( *)不是。

对于一般矩阵乘法:设AB 是两个大小合适的矩阵,使得A*B 存在。由于 timessum 支持整数,您可以概括上述技巧,使用 bsxfunsum 来计算产品矩阵的所有条目如下。

编辑:如 @July 所述,您需要在 sum 中添加 'native' 标志以保持整数类型的结果。也感谢您指出由 squeeze 引起的问题,现在已通过使用第二个 permute 纠正。

permute(sum(bsxfun(@times, A.', permute(B, [1 3 2])), 1, 'native'), [2 3 1])

例如:

>> 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

无论如何,最快的选择似乎是double(A)*double(B)

关于matlab - MATLAB 中整数值矩阵的乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19594568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com