如何在 MATLAB 乘法中使用 .*?

How to use .* in MATLAB multiplication?

我试图通过自己在 MATLAB 中实现瑞利分布的概率分布函数来可视化它,而不是使用内置的 raylpdf 函数。

瑞利分布PDF:

这是我的尝试:

function pdf = rayleigh_pdf(x)
    exp_term = -1*power(x,2)/(2*std(x))
    pdf = (x*exp(exp_term))/std(x)
end

但是当我尝试 运行 时,我得到一个错误:

x = linspace(-10,10,100);
plot(x,rayleigh_pdf(x))

错误:

Error using  * 
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of rows in the second matrix. To perform elementwise
multiplication, use '.*'.

我不确定为什么会收到此错误。我应该在哪里使用 .*?为什么需要它?

点前运算符允许进行 element-wise 运算,而不是默认的 matrix 运算。如果您编写的代码中没有点,则很有可能 运行 出现尺寸错误(例如,因为您尝试使用不匹配的尺寸进行矩阵乘法),或者由于以下原因而得到非常奇怪的结果自动广播,让你最终得到你没有预料到的大小的矩阵。

function pdf = rayleigh_pdf(x)
    exp_term = -x.^2./(2.*std(x).^2);
    pdf = (x.*exp(exp_term))./(std(x).^2)
end

两件小事:sigma-squared 通常表示方差,即标准差的平方。所以要么使用 std(x).^2 要么 var(x).
无需编写非常冗长的 power(x,2) 操作,您可以简单地使用 .^ 来获得元素明智的权力。

请注意,有些点是多余的,例如当您确定要处理整数时(在 MATLAB 中也称为 1 -by- 1 矩阵) .因此,您可以编写以下内容,这是等效的:

function pdf = rayleigh_pdf(x)
    exp_term = -x.^2/(2*std(x)^2);
    pdf = (x.*exp(exp_term))/(std(x)^2)
end

即只有在处理数组时才需要点,这里是 xexp_term,而不是像 2std(x).

这样的标量