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?

2 Answers 2

3

You can replace lines 3 to 6 with

listWorkspaceVariable = {S.name};

Also you can use ismember with two cell arrays so last line can be rewritten

compareCellArrayList = ismember(listWorkspaceVariable, listParam);

so it will be like

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

By the way, it seems that your function is not returning compareCellArrayList.

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

Comments

1

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

Comments

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.