matlabrandomline-segment

how to generate n samples from a line segment using Matlab


Given n samples of 100,how do we generate these random samples in the line segment below using matlab

line_segement:

x between -1 and 1, y=2


Solution

  • If you want to generate n random samples between to given limit (in your question -1 and 1), you can use the function rand.

    Here an example:

    % 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))
    

    In the example, the sort function is called to sort the values in order to have an ascendent series.

    x_min and (x_max-x_min) are used to "shift" the series of random values so that it belongs to the desired interval (in this case -1 1), since rand returns random number on an open interval (0,1).

    If you want to have a XY matrix composed by the random samples and the defined constant y value (2):

    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'})
    

    (in the picture, only 20 samples have been plot to make it more clear)

    enter image description here

    Hope this helps.