Search code examples
matlabsimulinkdynamic-variables

Matlab access dynamic variables


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.


Solution

  • 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