-1

If you define a range from A1 to A10 in Excel using VBA you cam use Range("A1:A10"). On the other hand side it's possible to write down Range("A1:A"&10). How can I use the second way in MATLAB, please?

I have some matrices M1, M2, M3, ..., and I wish to define them by using iterator FOR that helps me stop writing the matrix names completely.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Azkia
  • 3
  • 1
  • 4
    This is called **Dynamic Variable naming** which is [bad, very bad](https://stackoverflow.com/a/32467170/5211833). Don't name your variables like that. Either use sensible names per variable, or, if they are all the same but e.g. in different iterations of a program, use, in order of preference, a multi-dimensional matrix (if the sizes are equal), a `struct` with proper naming, or a `cell`. – Adriaan May 06 '19 at 13:05
  • 2
    Start with `M={M1,M2,M3,...}`, then you can iterate over the matrices with `M{index}`. – Cris Luengo May 06 '19 at 14:42

1 Answers1

-2

Notwithstanding the comment that this approach is frowned upon, below is a way to do it programmatically:

% define cell with matrix names
number_of_matrices_I_want = 5;
my_matrix_names = repmat({'NA'}, 1, number_of_matrices_I_want);
for ii = 1:length(my_matrix_names)
    my_matrix_names(ii) = {strcat('M',num2str(ii))};    
end

% example for how to populate a matrix from "my_matrix_names"
x = rand(5,1); % fake numbers
y = rand(5,1);
eval([my_matrix_names{1} '=  [x y]']);
a11
  • 3,122
  • 4
  • 27
  • 66