Paula
Paula

Reputation: 83

Eval ismember in a loop

I have 6 different arrays (double), with different sizes, called practice1, practice2, ..., practice6 and I need to compare each other to inspect whether they contain same numbers/values. I am trying to do a loop using the ismember and eval function such as below but I get the error "Undefined function 'eval' for input arguments of type 'logical". I would be grateful if someone could help me on how to do this!

allvariables = who('practice*')
for i=1:6
eval(ismember(allvariables{i}, allvariables{i+1}))

One other problem with my loop is that, as above, I am only comparing the current practice with the next one and not each practice with all the others. Probably there is a simpler way of doing this without a loop or a loop which covers all the possibilities?

Upvotes: 0

Views: 87

Answers (1)

Pursuit
Pursuit

Reputation: 12345

I think I see what's going on here. You need to either carefully construct your string, and then eval the whole thing, or eval the variable names and then call ismember.

Some examples are below:

%First some setup
practice_x= [1 2 3];
practice_y = [2 3 4];
practice_z = [1 4 5];
allvariables = who('practice*')
%    allvariables =
%      3×1 cell array
%        'practice_x'
%        'practice_y'
%        'practice_z'

%Option 1
for ix = 1:(length(allvariables)-1)
    eval(['ismember('  allvariables{ix} ', ' allvariables{ix+1} ')'])
end

%Option 1a (same as 1, but IMHO slightly easier to work with and explain on SO)
for ix = 1:(length(allvariables)-1)
    strTemp = ['ismember('  allvariables{ix} ', ' allvariables{ix+1} ')'];
    %When ix = 1, the strTemp variable contains the string below.
    %    strTemp =
    %    ismember(practice_x, practice_y)
    eval(strTemp )
end

%Option 2, use `eval` on the variable names directly
for ix = 1:(length(allvariables)-1)
    ismember(  eval(allvariables{ix}),   eval(allvariables{ix+1})   )
end

%For this example, all of these options result in the following output
%    ans =
%      1×3 logical array
%       0   1   1
%    ans =
%      1×3 logical array
%       0   0   1

Standard Pedantic Admonition:

Questions that involve storing information in variables names, forcing this type of manipulation of variable names as data, usually mean that the overall code is structured in a way that is, um, stressful and difficult to work with.

This works. This is consistent with Matlab's documented features. But somewhere in this code there are some strong anti-patterns with respect to how data is being handled and stored.

Upvotes: 2

Related Questions