Matlab通过在没有for循环的情况下多次迭代相同的命令来创建矩阵

Matlab create matrix by iterating the same command several times without for loop

我有这样的代码:

A = [sparse(round(rand(4,4)))];
B = [sparse(round(rand(1,4)))];
C = [bsxfun(@minus,A(1,:),B); bsxfun(@minus,A(2,:),B); bsxfun(@minus,A(3,:),B); bsxfun(@minus,A(4,:),B);]

是否可以在没有循环的情况下(因为循环会花费很长时间)以某种方式为大量行定义 C(这样我就无法以这种方式实际打印命令)?

如果将矩阵和行向量传递给 bsxfun,它会自动将向量应用于矩阵的所有行,因此只需使用:

C = bsxfun(@minus, A, B);

这会将行向量 B 减去矩阵 A 的所有行,无论您有多少行。

编辑:如果您有两个矩阵而不是一个矩阵和一个向量,您可以使用排列或 arrayfun。看看:

Multiply all columns of one matrix by another matrix with bsxfun

另一个选项:

如果您希望保留稀疏矩阵:

C = A - repmat(B,size(A,1),1); %but slower than the bsxfun version.