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
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/378241/image.png)
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
1 件のコメント
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!