Search code examples
matlaboctave

Octave Replace elements in a vector under certain circumstances


I have two vectors as below:

p = zeros(5,1);
hx = [0.1; 0.3; 0.7; 0.9; 0.2];

the task is to replace elements in p from 0 to 1 if elements in hx >=0.5. Expeted output:

p =

   0
   0
   1
   1
   0

It can be achieved by below code, what I don't understand is: as pos = find(hx >= 0.5); gives a 2D vector, how to understand p(pos,1)=1;? How could this final line of code knows which index of p corresponding to the right element in pos? There seems no obvious connection between those two. On the other hand, how could this be done through for loop and if statement?

pos = find(hx >= 0.5);  
p(pos,1)=1; 

Solution

  • find returns the a list of (linear) indices where the condition in the parentheses is true. In your case, this would be [3;4], since the condition is satisfied in element 3 and 4.

    The second line sets the elements with rows indicated by pos and column 1 to 1.

    You could do a loop

    for idx = 1:length(hx);
        if hx(idx) >=0.5
           p(idx,1) = 1;
        end
    end
    

    but this would be very un-Matlab/Octave. Much nicer would be

    p(hx>=0.5) = 1;
    

    which avoids the detour via find