For each random point, keep the random point if it is in the triangular region having vertices (0,0), (b,0) and (b,h), and if the random point is not in the triangular region, preform the appropriate transformation on the point to create a point that is in the triangular region.
Randomly chooses points from a triangular region and stores the x and y coordinates
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
My task is to write a MATLAB function where b and h are positive real numbers, n is a positive integer, and x and y are row vectors of length n. Program will randomly choose n points from the triangular region having vertices (0,0), (b, 0) and (b,h) and stores the x-coordinates and y-coordinates of the n points in the x and y vectors respectively in the order the points are chosen. I have a program written out that produces y-values, but I am not sure how to get both x and y values from the program.
Here is what I have so far:
function [x,y] = hw22(b,h,n)
%
rng('shuffle')
x = zeros(1,n);
y = zeros(1,n);
k = 1;
while k <= n
x(k) = h*rand;
y(k) = b*rand;
if y(k) < b/h*x(k)
k = k + 1;
end
end
Réponses (5)
Asad (Mehrzad) Khoddam
le 12 Oct 2020
function [x,y] = hw22(b,h,n)
%
rng('shuffle')
x = zeros(1,n);
y = zeros(1,n);
k = 1;
while k <= n
xr = h*rand;
yr = b*rand;
if yr < b/h*xr
x(k)=xr;
y(k)=yr;
k = k + 1;
end
end
0 commentaires
Ameer Hamza
le 12 Oct 2020
Modifié(e) : Ameer Hamza
le 12 Oct 2020
The code seems correct, just swap the h and b
[x, y] = hw22(1, 2, 1000);
plot(x, y, '+');
function [x,y] = hw22(b,h,n)
%
rng('shuffle')
x = zeros(1,n);
y = zeros(1,n);
k = 1;
while k <= n
x(k) = b*rand;
y(k) = h*rand;
if y(k) < h/b*x(k)
k = k + 1;
end
end
end
Bruno Luong
le 12 Oct 2020
Modifié(e) : Bruno Luong
le 12 Oct 2020
This is a direct method, no loop, no discard, etc...
n = 1e4;
b = 1;
h = 2;
w1=1-sqrt(rand(1,n));
w2=(1-w1).*rand(1,n);
w3=1-(w1+w2);
w=[w1;w2;w3];
% triangle coordinates
Txy =[0, b, b;
0, 0, h];
Rxy = Txy*w;
x = Rxy(1,:);
y = Rxy(2,:);
% Check
plot(x,y,'.')
0 commentaires
Asad (Mehrzad) Khoddam
le 12 Oct 2020
function [x,y] = hw22(b,h,n)
x=rand(n,1)*b;
y=rand(n,1).*x*h/b;
end
1 commentaire
Asad (Mehrzad) Khoddam
le 13 Oct 2020
function [x,y] = hw22(b,h,n)
x=rand(n,1)*b;
y=rand(n,1)*h;
ind=find(y>x*b/h);
x(ind)=b-x(ind);
y(ind)=h-y(ind);
end
0 commentaires
Voir également
Catégories
En savoir plus sur Graphics Performance dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!