如何使用Matlab从线段生成n个样本

时间:2015-10-18 16:10:56

标签: matlab random-sample line-segment

如果n个样本为100,我们如何使用matlab在下面的线段中生成这些随机样本

line_segement:

x在-1和1之间,y = 2

1 个答案:

答案 0 :(得分:2)

如果您要在给定限制(在您的问题n-1)之间生成1个随机样本,则可以使用函数rand

这是一个例子:

% Define minimum x value
x_min=-1
% Define maximum x value
x_max=1
% Define the number of sample to be generated
n_sample=100
% Generate the samples
x_samples = sort(x_min + (x_max-x_min).*rand(n_sample,1))

在示例中,调用sort函数对值进行排序,以便生成ascendent系列。

x_min(x_max-x_min)用于" shift"一系列随机值,使其属于所需的时间间隔(在本例中为-1 1),因为rand在开放时间间隔(0,1)上返回随机数。

如果你想要一个由随机样本和定义的常量y值(2)组成的XY矩阵:

y_val=2;
xy=[x_samples ones(length(x_samples),1)*y_val]

plot([x_min x_max],[y_val y_val],'linewidth',2)
hold on
plot(xy(:,1),xy(:,2),'d','markerfacecolor','r')
grid on
legend({'xy segment','random samples'})

(在图片中,只有20个样本已被绘制以使其更清晰)

enter image description here

希望这有帮助。