Search code examples
matlablistvariable-length-array

MATLAB: Loop through the values of a list from 'who' function


I have a long list of variables in my workspace. First, I'm finding the potential variables I could be interested in using the who function. Next, I'd like to loop through this list to find the size of each variable, however who outputs only the name of the variables as a string.

How could I use this list to refer to the values of the variables, rather than just the name?

Thank you,

list = who('*time*')
list = 

    'time'
    'time_1'
    'time_2'

for i = 1:size(list,1);
    len(i,1) = length(list(i))
end

len =

     1
     1
     1

Solution

  • If you want details about the variables, you can use whos instead which will return a struct that contains (among other things) the dimensions (size) and storage size (bytes).

    As far as getting the value, you could use eval but this is not recommended and you should instead consider using cell arrays or structs with dynamic field names rather than dynamic variable names.

    S = whos('*time*');
    
    for k = 1:numel(S)
        disp(S(k).name)
        disp(S(k).bytes)
        disp(S(k).size)
    
        % The number of elements
        len(k) = prod(S(k).size);
    
        % You CAN get the value this way (not recommended)
        value = eval(S(k).name);
    end