How do I create multiple matrices of different sizes?

6 views (last 30 days)
I am trying to generate multiple matrices using the 'rand' function. I need to create random matrices ranging from sizes 1-1000 (in increments of 1). My first thought was using the 'for' loop in order to generate so many matrices. One time in a class I had to generate only five random matrices (with a mean of 80 and a std of 15), so since there was only five, it was simple to generate. My code for those five was:
r_1 = 80 + 15. *randn (10,1);
r_2 = 80 + 15. *randn (20,1);
r_3 = 80 + 15. *randn (50,1);
r_4 = 80 + 15. *randn (100,1);
r_5 = 80 + 15. *randn (200,1);
However, now that I have to generate 1000 matrices, I am not sure how to correctly set up a 'for' loop. What I have so far is:
x = randn(1,1) : 1 : rand(1000,1)
a = 80 + 15.*randn(x)
for k = [1:1000]
ave = mean(a)
end
Thank you

Answers (1)

Stephen23
Stephen23 on 12 Mar 2015
Avoid creating dynamically named variables in MATLAB. This is poor practice as has been explained many times on this forum, and is not recommended by MATLAB themselves:
When you are a beginner it seems like a cunning and fast way to store information, but actually it is really bad practice to name your variables dynamically. MATLAB is also not intended for this kind of variable naming: if you continue to include data in the variable names then you will find yourself fighting many more of these battles against MATLAB.
However when you use more appropriate storage for your data (and meta-data) then you will suddenly find lots of MATLAB functions that do many useful operations for you, quickly and easily.
In your case a much more robust solution would be to use structures , where you can include fields for each kind of data (e.g. Process type, Flow data, Temperature data, Notes, Units, etc), or cell arrays . There are many functions that support working on structures and cell arrays, and can access these data easily, and they can also be used in vectorized code (which is something you need to learn about). And yes, you can even define structure fieldnames dynamically , and the structures can also be non-scalar !
Placing your data in a structure or cell array also makes it much easier to pass to functions: can you imagine the fight you would have trying to pass hundreds of dynamically named variables to a function?
If you have a newer version of matlab you can also use a table , which stores the data together in one array but also allows key-name access to the columns. This might be a good alternative for your data.
In case you are interested, here are some pages explaining why dynamically assigning variable names is a really bad idea in MATLAB:

Categories

Find more on Data Type Identification in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!