How to generate randomly placed circles and assign them a function-defined value

조회 수: 3 (최근 30일)
Hi, I want to create 20 circles of equal radius with randomly generated centers in a space 1 x 1 units large. I want to assign the area within each of these circles a value, say "4", which refers to a set of properties I've defined elsewhere. So, I have this:
radius = 0.01;
x_center = 0.5.*rand(1,1);
y_center = 0.5.*rand(1,1);
M((X-x_center)^2 + (Y-y_center)^2 <= radius^2) = 4;
The variables "X" & "Y" are required by the function "M". Running this in my code gives me 1 circle at a random location, but I want that repeated 20 times for other sets of random coordinates. I tried to just use rand(20,1) instead, but I got an error that my "arrays had incompatible sizes for the opteration," refering to (X-x_center) & (Y-y_center). It works when I use rand(1,1) because it produces a single value instead of an array. Could I use a for loop to generate all 20 circles?
  댓글 수: 1
Adam Danz
Adam Danz 2023년 4월 24일
If X and Y are scalars, you shouldn't have an issue
radius = 0.01;
x_center = 0.5.*rand(20,1);
y_center = 0.5.*rand(20,1);
M(((X-x_center).^2 + (Y-y_center).^2) <= radius.^2) = 4;
If X and Y are vectors that are longer or shorter than 20 values or other types of arrays, then you'll have the problem described in the error message.

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

채택된 답변

Rik
Rik 2023년 4월 24일
Just a clarification: M is not a function here, but a variable. Otherwise your code as posted would not work.
Putting this in a loop is trivial:
radius = 0.01;
for n=1:20
x_center = 0.5.*rand(1,1);
y_center = 0.5.*rand(1,1);
M((X-x_center)^2 + (Y-y_center)^2 <= radius^2) = 4;
end
Don't forget to explicitly assign zeros to M.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Discrete Data Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by