2

I have a lot of variables in the base workspace. I have a list of strings containing valid names. So let's say the base workspace contains the variable names var1, var2, var3, var4, var5, var6, var7, var8, var9, var10 and the list of strings is a cell array equal to :

listParam = {'var4' 'var7' 'var10'};

Now, I want to check if the strings that are in listParam have a corresponding declared variable in the base workspace. Here what I have done so far :

function [compareCellArrayList] = test(listParam)
S = evalin('base','whos'); % Looks for the variables in the base workspace
listWorkspaceVariable = cell(size(S)); % Pre-allocate
for ii = 1:length(S)
    listWorkspaceVariable{ii,1} = S(ii,1).name; % Gets the variable name of each variable
end
compareCellArrayList = cellfun(@(x) ismember(x, listParam), listWorkspaceVariable, 'UniformOutput', false);

The code above is working correctly, but it's just that i have a feeling it could be simplified while still being easy to understand. Any ideas?

4

2 回答 2

3

您可以将第 3 到 6 行替换为

listWorkspaceVariable = {S.name};

您也可以使用ismember两个单元格数组,因此可以重写最后一行

compareCellArrayList = ismember(listWorkspaceVariable, listParam);

所以它会像

function [listWorkspaceVariable] = test(listParam)
S = evalin('base','whos'); % Looks for the variables in the base workspace
listWorkspaceVariable = {S.name};
compareCellArrayList = ismember(listWorkspaceVariable, listParam);

顺便说一句,您的函数似乎没有返回compareCellArrayList

于 2013-08-29T15:55:24.283 回答
1

doesexist = ismember(listParam,{S.name})

于 2013-08-29T15:59:34.423 回答