Search code examples
matlabvectorindexingpositionelement

Matlab error using find command


I have the vector [0 0 1 1 0 1 1 0 1]. I would like to find indices of 0 and 1s. I have tried using the find command, but I am getting:

0x1 empty double column vector

Solution

  • While aahung's answer correctly returns the positions of the 0's and 1's, the typical use case for these indices would be choosing elements from another array that match these positions. If this is indeed the case, one should rely on logical indexing instead of find:

    tfArr = [0 0 1 1 0 1 1 0 1];
    data =  reshape(magic(3),1,[]); % [8,3,4,1,5,9,6,7,2]
    
    dataWhereOnes = data(logical(tfArr))
    % equivalently to the above : data(~~tfArr)
    dataWhereZeros = data(~tfArr)
    

    Which results in:

    dataWhereOnes =
         4     1     9     6     2
    
    dataWhereZeros =
         8     3     5     7