0

I am trying to access Matlab dynamically created variables but I am unable to do it. I know that in Matlab it's not ideal to create dynamic vars but in this case, it's pretty easy and comfy. to use them.

Let's say that the user can define a few points

point0 = [0,0,0;10,0,0];
point1 = [10,0,0;0,10,0];
point2 = [10,10,0;-10,0,0];

And what I want to do is to extract data from all of them in while cycle. But I don't know how to access them.

I tried

point[i](1,1); % access number from first column and first row.
point{i}(1,1);

And storing "point" + i in variable but nothing works. I will be thankful for any help.

  • 4
    dynamically created variables are a big nono. what you should do instead is do something that would make your last examples work. For example, creating a cell-array called `point`, or a 3D matrix called `point`. – Ander Biguri Nov 17 '20 at 15:50
  • 4
    This is precisely *why* it's considered not ideal to create dynamic variables. Accessing the variables is definitely *not* "easy and comfy". – beaker Nov 17 '20 at 15:52
  • Thanks for answers. That structure looks pretty nice. Going to try it. –  Nov 17 '20 at 16:01
  • Short note on why dynamic variables are horrible, see [this answer of mine](https://stackoverflow.com/a/32467170/5211833) and references therein. The gist is: it needs `eval`, which is horrible. That disables the JIT, makes for obscure code (i.e. hard debugging) and allows for possible harm up to and including formatting your computer. – Adriaan Nov 30 '20 at 15:41

1 Answers1

0

This code solution could work for you (based on recommendation from @Ander Biguri):

point1 = [0,0,0;10,0,0];
point2 = [10,0,0;0,10,0];
point3 = [10,10,0;-10,0,0];
% use
point_cell = {point1, point2, point3};  % 1x3 cell

% or 
point_cell_dynamic{1} = point1;         % 1x4 cell
point_cell_dynamic{2} = point2;  
point_cell_dynamic{3} = point3;  
point_cell_dynamic{4} = point3;  

point_cell{1}(1,1)                      % {point1} (row = 1 ,column = 1)  -> prints 0
point_cell{3}(2,1)                      % {point3} (row = 2 ,column = 1)  -> prints-10
User34563
  • 24
  • 1