2

I'd like to know how to find a variable in the base MATLAB Workspace by entering only a part of its name. I have a long list of variables & I don't know the exact variable name. Is there a function that compares/matches character order in a list of variable strings?

Thanks,

1 Answer 1

4

You can use who to obtain a list of all variable names currently in your workspace. From there, you can use regexpi to do a case insensitive regular expression lookup to find those variables that match your query. Something like:

namesWorkspace = who;
outStr = regexpi(namesWorkspace, 'nameOfVariable');
ind = ~cellfun('isempty',outStr);
vars = namesWorkspace(ind);

nameOfVariable is the name or partial name of the variable you are searching for. outStr will provide you with a cell array of elements that is the same size as the total number of variables in your workspace. If an element in this output cell array is empty, then the corresponding workspace variable wasn't matched. If it's non-empty, then there was a match. We simply go through this output cell array and determine which locations are non-empty, and we use these to index into our workspace names array to retrieve those final variables you want (stored in vars). cellfun allows you to iterate over every element in a cell array and apply a function to it. In this case, we want to check every cell to see if it's empty by using isempty. Because we want the opposite, we need to invert the operation, and so ~ is used.

For example, this is my workspace after recently answering a question:

names = 

    'O'
    'ans'
    'cellData'
    'idx'
    'names'
    'out'
    'possible_names'
    'possible_surnames'
    'student_information'

Let's find those variable names that contain the word possible:

outStr = regexpi(namesWorkspace, 'possible');
ind = ~cellfun('isempty',outStr);
vars = namesWorkspace(ind)

vars = 

    'possible_names'
    'possible_surnames'

Even simpler

Tip of the hat goes to Sam Roberts for this tip. You can simply apply the -regexp flag and specify the patterns you want to look for:

vars = who('-regexp', 'possible')

vars = 

'possible_names'
'possible_surnames'
Sign up to request clarification or add additional context in comments.

3 Comments

Great answer and explanation!
Even simpler: you can supply -regexp and an expression as input arguments to who, and it will only return variables that match. No need for two steps.
@SamRoberts - Interesting! Thanks for the tip Sam! I've edited my post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.