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
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)
Hope this helps.
Related
I would like to generate a vector of 20 random numbers knowing the standard deviation, the mean and contaning two 0 values. Is it possible?
These are the desired values of mean and standard deviation:
Mean: 3.3
Standard deviation: 25%
This seems to work fine: https://fr.mathworks.com/help/matlab/math/random-numbers-with-specific-mean-and-variance.html however, I need to have in my vector two 0 values.
You can do this in a few steps, as detailed in the comments. The "at least" two zeros condition is easier than "exactly" two zeros would be - in the latter case you would have to write a quick function to return randn values except zero and then make sure the distribution shifting doesn't create new zeros.
% Create an array of length N+z (=20 here), which is N=18 randn values and z zeros
% Could make this more complicated to limit/expand on specific values
N = 18;
z = 2;
v = [randn(N,1); zeros(z,1)];
% Define a target mean (mu) and standard dev (sd)
mu = 3.3;
sd = 25;
% We have to iterate several times (100 is arbitrary) to get closer to both
% the s.d. and mean criteria. More passes for arbitrary accuracy
for ii = 1:100
% Scale the vector to satisfy the standard dev
v = sd*v/std(v);
% Shift the vector to satisfy the mean, but only the non-zero randn values
v(1:N) = v(1:N) - mean(v(1:N)) + ((N+z)/N)*mu;
end
% Output check
fprintf( 'Standard dev: %.4f\nMean: %.4f\n', std(v), mean(v) );
% >> Standard dev: 25.0000
% >> Mean: 3.3000
Note that by forcing specific values this isn't necessarily a perfectly normally distributed set of numbers any more, but it does satisfy your mean and standard deviation conditions. This is an issue with your problem statement - any solution will have this footnote.
The instructions are:
Create a random signal with the maximum amplitude value of (15 *0.1) with 11 sample values and center the middlemost value in the 0 of the x-axis. Write down the random values in the given format below.
x(n)=[values]
Plot the graph x[n] to show the 11 samples in a stem graph. Then do the following operations:
Plot the graph x[2n] to show the 11 samples in a stem graph.
Plot the graph x[n/2] to show the 11 samples in a stem graph.
Plot the graph x[n-3] to show the 11 samples in a stem graph.
Plot the graph x[n+2] to show the 11 samples in a stem graph.
The graphs should look similar to the graphs in this link:
https://cnx.org/contents/KilsjSQd#6.2:e6-BCH5U#1/Discrete-Time-Signal-Operations
for x[2n] i tried
xn=(15 *0.1).*rand(1,11); to create the random values
n=(-5:5);
n1 = 2*n;
stem(n1,xn);
the n values were just multiplied by two and all values of xn were still plotted, which is not supposed to be the case according to the link that I provided.
There are 2 key points I think you are missing:
If you are going to decimate your random numbers by a factor of 2, you need to start with twice as many points if you are going to end up with 11 points.
Multiplying the index by 2 does not discard every other point.
Here is some code that demonstrates making more random points so you end up with the right number after decimation, and creating a use variable that is not incremented by 1 so that you can decimate.
c = 2; % decimation factor
num_pts_after_dec = 11;
num_pts_before_dec = num_pts_after_dec * c;
xn=(15 *0.1) * rand(1, num_pts_before_dec);
use = 1:c:length(xn); % Create index for the decimation
xn = xn(use); % Do the decimation
n=(1:length(xn)) - (num_pts_after_dec + 1) / 2;
stem(n,xn);
I have a dataset with 3-hourly precipitation amounts for the month of January in the period 1977-1983 (see attachment). However, I want to generate precipitation data for the period 1984-1990 based upon these data. Therefore, I was wondering if it would be possible to create a custom made probability density function of the precipitation amounts (1977-1983) and from this, generate random numbers (precipitation data) for the desired period (1984-1990).
Is this possible in Matlab and could someone help me by doing so?
Thanks in advance!
A histogram will give you an estimate of the PDF -- just divide the bin counts by the total number of samples. From there you can estimate the CDF by integrating. Finally, you can choose a uniformly distributed random number between 0 and 1 and estimate the argument of the CDF that would yield that number. That is, if y is the random number you choose, then you want to find x such that CDF(x) = y. The value of x will be a random number with the desired PDF.
If you have 'Statistics and Machine Learning Toolbox', you can evaluate the PDF of the data with 'Kernel Distribution' method:
Percip_pd = fitdist(Percip,'Kernel');
Then use it for generating N random numbers from the same distribution:
y = random(Percip_pd,N,1);
Quoting #AnonSubmitter85:
"estimate the CDF by integrating. Finally, you can choose a uniformly
distributed random number between 0 and 1 and estimate the argument of
the CDF that would yield that number. That is, if y is the random
number you choose, then you want to find x such that CDF(x) = y. The
value of x will be a random number with the desired PDF."
%random sampling
N=10; %number of resamples
pdf = normrnd(0, 1, 1,100); %your pdf
s = cumsum(pdf); %its cumulative distribution
r = rand(N,1); %random numbers between 0 and 1
for ii=1:N
inds = find(s>r(ii));
indeces(ii)=inds(1); %find first value greater than the random number
end
resamples = pdf(indeces) %the resamples
So I need to generate a matrix of x and y points given that they meet the condition that at these (x,y) points concentration is greater than 10. Note that I first run a code that gives me concentration at each location, and now I need Matlab to "randomly" pick (x,y) points with the above condition.
Would appreciate any suggestions on how to go about this.
assuming your data looks something like this :
data= [... x y concentration
1, 1, 1; ...
2, 1, 11; ...
1, 2, 12; ...
2, 2, 1 ...
]
You could find all concentrations bigger than 10 with:
data_cbigger10=data(data(:,3)>10,:) % using logical indexing
and choose a random point from there with:
randomPoint=data_cbigger10(ceil(size(data_cbigger10,2)*rand),:) % pick a random index
If the dimensions are as follows:
the dimension of concentration is 52x61x61 as concentration is c(x,y,time), that of x is 1x61 and 1x52 for y. #PetrH – s2015
this should do the trick:
This is your data, I just make something up:
x=linspace(0,1,61);
y=linspace(0,1,52);
con=20*rand(61,52);
Now I find all positions in con which are bigger than 10. This results in a logical matrix. By multipling it with an random matrix the same size I get a matrix with random values where 'con' is bigger than 10, but everywhere else equals zero.
data_cbigger10=rand(size(con)).*(con>10);
by finding the max, or min, Value a random point is choosen:
for n=1:1:10
data_cbigger10=rand(size(con)).*(con>10);
[vals,xind]=max(data_cbigger10);
xind=squeeze(xind);
[vals,yind]=max(squeeze(vals));
[~,time_ind]=max(squeeze(vals));
yind=yind(time_ind);
xind=xind(yind,time_ind);
x_res(n)=x(xind)
y_res(n)=y(yind)
time_res(n)=time(time_ind)
con_res(n)=con(xind,yind,time_ind)
con(xind,yind,time_ind)=0; % setting the choosen point to zero, so it will not be choosen again.
end
Hope this works now for you.
Assuming you have the concentration for each point (x,y) stored in an array concentration you can use the find() and randsample() functions like so:
conGT10 = find(concentration>10); % find where concentration is greater than 10 (gives you indices)
randomPoints = randsample(conGT10,nn); % choose nn random numbers from those that satisfy the condition
x1 = x(randomPoints); % given the randomly drawn indices pull the corresponding numbers for x and y
y1 = y(randomPoints);
EDIT:
The above assumes that arrays x, y, and concentration are 1d and of the same length. Apparently this is not true for your problem.
You have a grid of points on a (x,y) plane and you measure concentration on this grid in different time periods. So the length of x is nx, the length of y is ny and the size of concentration is nx by ny by nt. For simplicity I will assume that you measure concentration only once, i.e. nt=1 and concentration is only 2d array.
The modified version of my previous answer would then be as follows:
[rows,cols] = find(concentration>10); % find where concentration is greater than 10 (gives you indices)
randomIndices = randsample(length(rows),nn); % choose nn random integers from 1 to n, where n is the number of observations that satisfy the condition 'concentration>10'
randomX = x(rows(randomIndices));
randomY = y(cols(randomIndices));
I am new in matlab and I am making a gremetric simulation with k = m2 and p = 1/5.
I have to generate 1000 random numbers and I must show them in a histogram with 15 number of cells. this is what I have so far:
K = 2;
P 1/5;
R = geornd(p,k,1000);
now I am trying to show these result in a histogram with 15 cells but I dont know how to do it please help.
EDIT:
to get the histogram I used:
hist(Sc,15), and this is the results:
According to the doc for geornd, you need to provide the function with a probability parameter P (here 1/5) and a vector dictating the size of the output you want, so it looks like your K is not used correctly in this context.
If you want 1000 random values distributed according to geornd, you might want to use this instead:
R = geornd(0.2,[1 1000]); % P of 0.2 and array of 1 x 1000 numbers
hist(R,15)
Which gives the following:
If you do want do generate 2 distributions, then you can calculate them all at once and plot them separately:
R = geornd(0.2,[2 1000]);
% Plot 1st distribution:
hist(R(1,:),15)
Plot 2nd distribution:
hist(R(2,:),15)