如何计算两个二进制向量的外积 [英] How to compute the outer product of two binary vectors

查看:154
本文介绍了如何计算两个二进制向量的外积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在生成一个随机的二进制矩阵,每行中都有一个特定数目的1.现在,我想将矩阵中的每一行乘以其转置(即row1'*row1).

I am generating a random binary matrix with a specific number of ones in each row. Now, I want to take each row in the matrix and multiply it by its transpose (i.e row1'*row1).

因此,我正在使用row1=rnd_mat(1,:)来获取第一行.但是,在乘法步骤中,我得到了这个错误

So, I am using row1=rnd_mat(1,:) to get the first row. However, in the multiplication step I get this error

两个逻辑输入都必须是标量的.要计算元素时间TIMES,请改用TIMES(.*)."

"Both logical inputs must be scalar. To compute elementwise TIMES, use TIMES (.*) instead."

知道我不想按元素计算,我想使用外部乘积生成一个矩阵.我尝试使用[0 0 1 ...]手动编写row1,并尝试查找外部产品.我设法得到了想要的矩阵.

Knowing that I don't want to compute element-wise, I want to generate a matrix using the outer product. I tried to write row1 manually using [0 0 1 ...], and tried to find the outer product. I managed to get the matrix I wanted.

那么,有人对我该怎么做有想法吗?

So, does anyone have some ideas on how I can do this?

推荐答案

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.

这篇关于如何计算两个二进制向量的外积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆