Search code examples
matlabmatlab-guidematlab-deploymentmatlab-compiler

how to check if all elements in an array are 1 or -1 in Matlab


I want to check if all elements in an array are 1 or -1, and if even one of them is still any value except 1 or -1, the function should continue. I wrote this piece of code:

while (all(initial_color(:))~=1 || -1 )

THE FUNCTION

end

Initial_color is the name of the array. But it is not working correctly, because I can see that all elements have turned to 1 or -1 but it still runs the function. I am new to Matlab, could you please help me with it? Thanks in advance.


Solution

  • The condition to test for is as follows:

    all( initial_color==1 | initial_color==-1 )
    

    Here you create two arrays, one is true for all elements of value 1, one is true for all elements of value -1. The | element-wise OR operator combines these into a single array. All of the elements must be true, hence all.

    You can also use unique, which returns the sorted set of unique values. This must be either [-1,1], [1] or [-1]. setdiff then can remove the elements -1 and 1 from the set, if the result is empty, there are no values different from 1 or -1:

    u = unique(initial_color);
    u = setdiff(u,[-1,1]);
    result = isempty(u);
    

    Note that unique is actually redundant here, setdiff returns the unique set also. This makes it a little easier to convert into a one-liner that fits within your while:

    isempty(setdiff(initial_color,[-1,1]))
    

    The setdiff approach is likely faster than the two comparisons, but I haven't tested this.