MATLAB: How to generate multiple sets of arrays automatically

arraydynamic variable namedynamic variablesevalmultiple arrayscattervariables in loop

The code currently generates a random scatter of 30 points. An array of x and y values are saved separately in x1 and y1.
I want to make multiple sets of x and y coordinates, so I can have multiple different arrays. For example if I wanted three different random scatters, the code would generate the arrays x1, y1, x2, y2, x3, y3, or if I wanted ten, then there would be ten x y pairings. And each pairing would generate a random scatter of points.
If anyone would be able to advise me, that would be great! I tried making a second for loop, but I couldn't figure out how to make it work… Here's the code I have written so far:
n = 30; %number of elements
R = 0.3; %maximum radius
x1 = zeros(n,1);
y1 = zeros(n,1);
for i = 1:1:n
x1(i) = unifrnd(-R,R);
y1(i) = unifrnd(-R,R);
end
figure(1)
plot(x1,y1, '.')
%save('optArray','x1','y1')
Thanks in advance for your help!

Best Answer

Here is your code, with a small change to store the data values in matrices:
M = 10; % number of repetitions
N = 30; % number of elements
R = 0.3; % maximum radius
X = zeros(N,M); % changed to matrix

Y = zeros(N,M); % changed to matrix
C = cell(1,M);
for m = 1:M
for n = 1:N
X(n,m) = unifrnd(-R,R);
Y(n,m) = unifrnd(-R,R);
end
C{m} = sprintf('test %d',m);
end
figure(1)
plot(X,Y, '.')
legend(C,'Location','BestOutside')
%save('optArray','X','Y','C')
I also plotted them all in one figure, and included a legend. Note how easy this was to do!
Do NOT use Dynamically Named Variables
Using dynamically named variables would make all of this much more complicated, slower, and buggier. In fact you should NOT create variable names dynamically (such as X1, X2, X3, etc), because although beginners all seem to believe that this is a great idea it really is not. Creating dynamic variable names is slow, buggy, and hard to read. Here is an explanation of why creating variable names dynamically is such a bad way to write code:
Related Question