How to generate randomly placed circles and assign them a function-defined value
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Maddie Kern
am 24 Apr. 2023
Kommentiert: Adam Danz
am 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:
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 Kommentar
Adam Danz
am 24 Apr. 2023
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.
Akzeptierte Antwort
Rik
am 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:
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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Discrete Data Plots finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!