Assigning value to array by logical indexing doesn't work

前端 未结 1 1015
忘了有多久
忘了有多久 2021-01-24 01:40

In Matlab, I want to replace a certain value with some other value.

I know that I can do this:

X(X==0) = -1 

If I want to replace all

相关标签:
1条回答
  • 2021-01-24 02:22

    Why your approach was not working is indeed a little curios. The reason is that the left hand side of your equation is completely logical, the right hand side is casted logical as well and

    logical(-1) = 1
    

    Therefore:

    Y = (X == 5)    %// Y is logical
    Y(Y == 0) = -1  %// Y is logical, Y == 0 is logical, 
                    %// -1 is casted to logical and logical(-1) = 1
    

    So transform your first logical array to double, and it works.

    Y = (X == 5)    %// Y is logical
    Y = double(Y)   %// Y is double
    Y(Y == 0) = -1  %// Y is double, Y == 0 is logical
    

    Example:

    X = randi(9,20,1);
    Y = (X == 5)   
    Y = double(Y)   
    Y(Y == 0) = -1  
    out = [X Y]
    

    out =
    
         7    -1
         3    -1
         5     1
         7    -1
         9    -1
         9    -1
         5     1
         2    -1
         2    -1
         3    -1
         8    -1
         3    -1
         8    -1
         3    -1
         9    -1
         4    -1
         2    -1
         3    -1
         6    -1
         5     1
    
    0 讨论(0)
提交回复
热议问题