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