Generate and Plot N Points Picking Random Points on Triangle

My task is to write a function that takes as input a positive integer n. We are asked to consider the traingle whose corner points are (0,0), (2,0), and (1,2). Let p0 = (1,1). The function's purpose is to generate and plot n points p1,p2, ... pn where pk is the point determined by randomly picking one of the three corners of the triangle, and letting pk be the midpoint between the chosen corner point and pk-1 for 1 <= k <= n. I have a small program written, but I have no clue where to go from there. Please help me to get started on finding a program that works. I am aware that this program does not do what I want, it is just a starting point. Here is what I have so far:
function ex3(n)
%
%
rng('shuffle')
x = zeros(1,n);
y = x;
k = 1;
while k <=n
x(k) = 2*rand;
y(k) = 1*rand;
if y(k) > 1/2*x(k)
k = k + 1;
end
end
Border_x = [0,2,2,0];
Border_y = [0,0,1,0];
plot(Border_x,Border_y,'r',x,y,'b.','markersize',1)
axis tight
axis equal

댓글 수: 1

I would appreciate a starting point and I should be able to figure out a program from there. Thank you.

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

 채택된 답변

Alan Stevens
Alan Stevens 2020년 10월 22일
More like the following;
rng('shuffle');
n = 1000; % Set number of points as desired
% Let (0,0) be vertex 1, (0,2) be vertex 2, (1,2) be vertex 3
X = [0 2 1];
Y = [0 0 2];
x = zeros(1,n);
y = x;
x(1) = 0.5; y(1) = 0.1; % starting point (change as desired)
for i = 2:n
p = randi(3,1); % Choose 1 2 or 3 at random
x(i) = (X(p) + x(i-1))/2;
y(i) = (Y(p) + y(i-1))/2;
end
Border_x = [0,2,1,0];
Border_y = [0,0,2,0];
plot(Border_x,Border_y,'r',x,y,'b.','markersize',1)
axis tight
axis equal
This generates a triangular Sierpinski gasket (better with a larger value of n). See what effect changing the starting point has.

댓글 수: 7

This program did not work for me. Is there an alternative to this program that would also work?
Strange! What was the error message?
I’m sorry I noticed a typo in one of my lines. This program works, thank you for the help!
Thank you for the program, but it only covers part of the triangle's area (see attached). How could one make it cover the whole area?
Many thanks and kind regards,
Ana
openfig('untitled.fig');
Torsten
Torsten 2023년 2월 14일
편집: Torsten 2023년 2월 14일
The object you've been asked to generate is known as a Sierpinski triangle. It is a fractal structure. The gaps are an intrinsic part of it!
The object you've been asked to generate is known as a Sierpinski triangle.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Discrete Data Plots에 대해 자세히 알아보기

질문:

2020년 10월 22일

댓글:

2023년 2월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by