如何用matlab画一个函数的密度图
时间: 2023-05-27 22:06:28 浏览: 105
1. 首先,我们需要定义一个函数。例如,我们可以定义一个正态分布函数:
```
function y = normal_distribution(x, mu, sigma)
y = exp(-(x-mu).^2/(2*sigma^2))/(sigma*sqrt(2*pi));
end
```
这个函数的参数分别为 `x`,`mu` 和 `sigma`,代表自变量、均值和标准差。
2. 接下来,我们需要生成一些数据来绘制密度图。我们可以使用 `normrnd` 函数生成一些符合正态分布的随机数:
```
data = normrnd(0, 1, 1000, 1);
```
这个语句会生成一个 1000 行 1 列的数组,每个元素都是符合均值为 0,标准差为 1 的正态分布的随机数。
3. 现在我们可以使用 `ksdensity` 函数计算密度估计:
```
[f, x] = ksdensity(data);
```
这个语句会返回密度估计的值 `f` 和对应的自变量 `x`。
4. 最后,我们可以使用 `plot` 函数绘制密度图:
```
plot(x, f);
```
这个语句会绘制密度估计值 `f` 对应的自变量 `x` 的图像。
完整代码如下:
```
function y = normal_distribution(x, mu, sigma)
y = exp(-(x-mu).^2/(2*sigma^2))/(sigma*sqrt(2*pi));
end
data = normrnd(0, 1, 1000, 1);
[f, x] = ksdensity(data);
plot(x, f);
```
运行代码后会得到一个正态分布的密度图。
阅读全文
相关推荐














