MATLAB Answers

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

1 view (last 30 days)
Sophie Culhane
Sophie Culhane on 12 Oct 2020
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 Comment

Sophie Culhane
Sophie Culhane on 12 Oct 2020
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.

Sign in to comment.

Answers (5)

Asad (Mehrzad)  Khoddam
Asad (Mehrzad) Khoddam on 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 Comments

Sign in to comment.


Ameer Hamza
Ameer Hamza on 12 Oct 2020
Edited: Ameer Hamza on 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
Bruno Luong on 12 Oct 2020
Edited: Bruno Luong on 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 Comments

Sign in to comment.



Asad (Mehrzad)  Khoddam
Asad (Mehrzad) Khoddam on 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 Comments

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!