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
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
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 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Discrete Data Plots についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!