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 次查看(过去 30 天)
显示 更早的评论
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
回答(5 个)
Asad (Mehrzad) Khoddam
2020-10-12
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 个评论
Ameer Hamza
2020-10-12
编辑:Ameer Hamza
2020-10-12
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
2020-10-12
编辑:Bruno Luong
2020-10-12
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 个评论
Asad (Mehrzad) Khoddam
2020-10-12
function [x,y] = hw22(b,h,n)
x=rand(n,1)*b;
y=rand(n,1).*x*h/b;
end
Asad (Mehrzad) Khoddam
2020-10-13
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Performance 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!