Reputation: 497
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;
Upvotes: 3
Views: 6363
Reputation: 23
The easiest solution I could find without loops is this:
p = hx >= 0.5
It will output a vector of the same size as hx but with ones where the condition was met.
Upvotes: 1
Reputation: 255
This can be solved in a single line of code. But make sure p and hx have equal number of elements.
p(hx>=0.5)=1;
Upvotes: 1
Reputation: 11
I had the same problem and solved using following code snippet:
VectorWithZeros = VectorWithZeros + ReplaceWithScalar * (VectorWithZeros == 0)
Upvotes: 0
Reputation: 74930
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
Upvotes: 7