Search code examples
matlabmatrixrandomcall

Calling data with using randi command in Matlab


I want to call data in the matrix by using a string which is defined by 'randi' command.

   A=[1 2]
   B=[2 3]
   C=[3 5]

   corners = 'ABC'
   randompick = corners(randi(numel(corners)))
   disp(randompick)
   randompick(1) 

I want as an example for A matrix:

   1

So desired result is the same as what A(1), B(1) or C(1) give. What's wrong in this script? Thanks.


Solution

  • The problem here is that you conflate code and data. randompick contains data, and A is a variable name, code.

    There is a way to do exactly what you're thinking, and that involves the use of eval. This is not recommended exactly because it conflates code and data. This leads to complicated code that is hard to read and hard to debug. Don't do it! Fortunately there are alternatives.

    One simple approach is to store your data arrays in a larger array, for example a cell array:

    data = { [1 2]
             [2 3]
             [3 5] };
    randompick = randi(numel(data))
    data{randompick}(1)
    

    If the name A/B/C is important, then you have yet another reason to avoid using that as a variable name. It's data! Consider, for example, using a struct array:

    data = struct('name', {'A','B','C'}, ...
                  'values', { [1 2]
                              [2 3]
                              [3 5] });
    randompick = randi(numel(data))
    disp(data(randompick).name)
    data(randompick).values(1)
    

    Yet another approach is to use a map (also called a dictionary, or hash table):

    data = containers.Map({'A','B','C'}, ...
                          { [1 2]
                            [2 3]
                            [3 5] });
    corners = 'ABC'
    randompick = corners(randi(numel(corners)))
    disp(randompick)
    data(randompick)