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

2 views (last 30 days)
Maddie Kern on 24 Apr 2023
Commented: Adam Danz on 24 Apr 2023
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:
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?
Adam Danz on 24 Apr 2023
If X and Y are scalars, you shouldn't have an issue
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 on 24 Apr 2023
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:
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.