Randomly chooses points from a triangular region and stores the x and y coordinates

조회 수: 1(최근 30일)
Sophie Culhane 2020년 10월 12일
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
댓글 수: 1표시숨기기 없음
Sophie Culhane 2020년 10월 12일
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.

댓글을 달려면 로그인하십시오.

답변(5개)

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표시숨기기 이전 댓글 수: -1

댓글을 달려면 로그인하십시오.

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
댓글 수: 1표시숨기기 없음
Sophie Culhane 2020년 10월 12일
Thank you!

댓글을 달려면 로그인하십시오.

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표시숨기기 이전 댓글 수: -1

댓글을 달려면 로그인하십시오.

function [x,y] = hw22(b,h,n)
x=rand(n,1)*b;
y=rand(n,1).*x*h/b;
end
댓글 수: 1표시숨기기 없음
Bruno Luong 2020년 10월 13일
This code won't give uniform distribution on triangle

댓글을 달려면 로그인하십시오.

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

댓글을 달려면 로그인하십시오.

범주

Find more on Annotations in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by