How to create multiple blank matrices using loop ?
8 views (last 30 days)
Show older comments
I Need to create multiple blank matrices so that i can extract data onto the matices and use it for later use. I cant find comands to create multiple matrices of different names names being A1,A2,A3 etc.
1 Comment
Stephen23
on 23 Jan 2019
Edited: Stephen23
on 23 Jan 2019
"...create multiple matrices of different names names being A1,A2,A3 etc. "
Dynamically creating variable names like that is one way that beginners force themselves into writing slow, complex, obfuscated, buggy code that is hard to debug. The MATLAB documentation specifically recommends against magically creating variable names like that: "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended. The preferred method is to store related data in a single array."
Note that forcing a number into the variable name is treating that number as a pseudo-index, which all experienced users know is much better written as a real index into one variable. Real indexing is neat, simple, very fast, efficient, and much simpler to debug, and will make your MATLAB code simpler and more efficient. Unlike what you are trying to do.
Read this to know more:
"I Need to create multiple blank matrices"
MATLAB does not have a concept of "blank matrices": all matrices contain data. However it is certainly easy to preallocate matrices:
Answers (1)
KSSV
on 23 Jan 2019
YOu need not define A1,A2 A3 etc.....you need to initialize a 3D matrix. For EXample:
A = rand(2,2,3) ;
A1 = A(:,:,1) ;
A2 = A(:,:,2) ;
A3 = A(:,:,3) ;
2 Comments
Stephen23
on 23 Jan 2019
Edited: Stephen23
on 23 Jan 2019
"The matrice name changing with every iteration"
Magically changing variable names is one way that beginners force themselves into writing slow, complex, obfuscated, buggy code. Do not do this if you want to learn how to use MATLAB effectively and actually spend your time on more useful things than chasing down pointless bugs.
The best solution is probably to use one ND array, or possibly one cell array, with some simple and efficient indexing. For example, you could use a cell array:
A = cell(1,12);
Note how this is already simpler than what you were attempting to do in a loop!
See Also
Categories
Find more on Matrix Indexing 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!