Search code examples
matlabcell-array

How do I replace cells in an array based on some criteria?


I have the cell array:

im = {'A+' NaN 'B-'; NaN NaN NaN; NaN 'A+' 'B+'; 'B+' NaN 'A-'; 'B+' NaN NaN; 'B-' 'A-', NaN}

from which I obtain:

refPoints = find(( any(strcmp('A+', im),2) | any(strcmp('A-', im),2)) & (any(strcmp('B+', im),2) | any(strcmp('B-', im),2)))

which gives:

refPoints = [1;3;4;6]

Now, I want to loop through im so as to invalidate points that are too close (say by a factor of 1), and then replace their corresponding cells with NaN.

In the given example, refPoints 3 and 4 are close, hence should be invalidated. I would thus expect my final result to be:

im = {'A+' NaN 'B-'; NaN NaN NaN; NaN NaN NaN; NaN NaN NaN; 'B+' NaN NaN; 'B-' 'A-', NaN}

and

refPoints = [1;6]

I have tried the following code:

 for ii = 1: size(im, 1)-1

    if find(( any(strcmp('A+', im(ii,:))) | any(strcmp('A-', im(ii,:)))) & (any(strcmp('B+', im(ii,:))) | any(strcmp('B-', im(ii,:)))))==true ...
         & find(( any(strcmp('A+', im(ii+1,:))) | any(strcmp('A-', im(ii+1,:)))) & (any(strcmp('B+', im(ii+1,:))) | any(strcmp('B-', im(ii+1,:)))))==true

    im(ii,:) ={NaN};

   end

end

This however does as expected for the 3rd row but not the 4th row. I do not know what exactly I am doing wrong here, but I have no idea what else to do.

Please any help, suggestions or advice on this is very much appreciated? Thank you in advance.  


Solution

  • This problems is very close to your previous question, but I hope this slightly different answer will be helpful for you.

    You can solve this problem by introducing the state variable isPreviousToClose as follows:

    isPreviousToClose = false;
    for ii = 1: size(im, 1)-1
    
        if (( any(strcmp('A+', im(ii,:))) || any(strcmp('A-', im(ii,:)))) && (any(strcmp('B+', im(ii,:))) || any(strcmp('B-', im(ii,:))))) ...
             && ( isPreviousToClose || (( any(strcmp('A+', im(ii+1,:))) || any(strcmp('A-', im(ii+1,:)))) && (any(strcmp('B+', im(ii+1,:))) || any(strcmp('B-', im(ii+1,:))))))
            isPreviousToClose = true;
            im(ii,:) ={NaN};
        else
            isPreviousToClose = false;
        end
    end
    if (isPreviousToClose)
        im(end,:) ={NaN};
    end
    

    The current line is set to NaN, if the next or the previous line is close.