Find variables in base Workspace with partial string match (Matlab)

最后都变了- 提交于 2019-12-01 11:28:13

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'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!