带有 meshgrid 的标量向量乘法 (Matlab)

Scalar-Vector multiplication with meshgrid (Matlab)

我有一个表达式,例如 s=aU+bV,其中 ab 是标量,UV 三分量向量。输出 s 显然是一个 3 分量向量。假设我想绘制 s 的第一个组件,看看当我更改 ab.

时它有何变化

为了绘图,我必须使用 surf,它采用矩阵作为变量 a b。所以我尝试用 meshgrid:

创建矩阵
A=0:10;
B=1:10;
[a,b]=meshgrid(A,B);

U=[1,1,0];
V=[1,0,1];

s = a*U + b*V;

这显然行不通,因为在这种情况下矩阵乘积和元素乘积都没有明确定义。我实际上如何使表示网格 a b 的矩阵逐个元素地乘以向量 UV?

您想使用逐元素乘法 (.*),因为您仍想将 ab 视为标量(即单独使用每个元素)。

您可以制作 3D 输出,其中每个 2D 切片对应于您的 meshgrid 输出,每个 UV 的分量一个切片。因此在这个例子中得到一个 10*11*3 矩阵。

为此,reshape UV 向量的大小 1*1*3

U = reshape( [1,1,0], 1, 1, [] ); % Or equivalently U(1,1,:) = [1,1,0]
V = reshape( [1,0,1], 1, 1, [] ); % Or equivalently U(1,1,:) = [1,0,1]

然后进行逐元素乘法

s = a.*U + b.*V;

注意:在 MATLAB R2016b 之前(引入隐式扩展时)您必须使用 bsxfun 来获得等效项:

s = bsxfun( @times, a, U ) + bsxfun( @times, b, V );

然后您可以绘制 S 的第 i 个元素,通过绘制 s(:,:,i).

随着 AB 变化

您可以使用 3D 矩阵来完成:

[A,B] = meshgrid(0:10,1:10);
U(1,1,:) = [1,1,0];
V(1,1,:) = [1,0,1];
s = A.*U + B.*V;
% s is now a NxMx3 matrix, where N = length(A) and M = length(B)

% We can plot how s varies with a and b as follows
surf(A,B,s(:,:,1)); % first component
surf(A,B,s(:,:,2)); % second component
surf(A,B,s(:,:,3)); % third component