且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何计算两个二进制向量的外积

更新时间:2023-11-08 22:32:28

MATLAB不支持logical矩阵或向量的矩阵乘法.这就是为什么您会收到该错误的原因.您需要先将矩阵转换为double或其他有效的数字输入,然后再尝试执行该操作.因此,请执行以下操作:

Matrix multiplication of logical matrices or vectors is not supported in MATLAB. That is the reason why you are getting that error. You need to convert your matrix into double or another valid numeric input before attempting to do that operation. Therefore, do something like this:

rnd_mat = double(rnd_mat); %// Cast to double
row1 = rnd_mat(1,:);
result = row1.'*row1;

您实质上要计算的是两个向量的外积.如果要避免强制转换为double,请考虑使用 bsxfun 为您代劳:

What you are essentially computing is the outer product of two vectors. If you want to avoid casting to double, consider using bsxfun to do the job for you instead:

result = bsxfun(@times, row1.', row1);

这样,您无需在制作外部产品之前就转换矩阵.请记住,两个向量的外积只是两个矩阵的逐元素相乘,其中一个矩阵由行向量组成,其中每一行是行向量的副本,而另一个矩阵是列向量,其中每一列是列向量的副本.

This way, you don't need to cast your matrix before doing the outer product. Remember, the outer product of two vectors is simply an element-wise multiplication of two matrices where one matrix is consists of a row vector where each row is a copy of the row vector while the other matrix is a column vector, where each column is a copy of the column vector.

bsxfun自动广播每个行向量和列向量,以便我们产生两个维数兼容的矩阵,并逐个元素相乘,从而产生外积.

bsxfun automatically broadcasts each row vector and column vector so that we produce two matrices of compatible dimensions, and performs an element by element multiplication, thus producing the outer product.