Use of logical vector:
Determine how many elements in the vector vec were greater than 5, the sum function can be used on the resulting vector isg:
>> sum(isg)
ans =
3
The logical vector isg can also be used to index into the vector. For illustration, when only the elements from the vector which are greater than 5 are preferred:
>> vec(isg)
9 6 11
As the values in the vector should be logical 1's and 0's, the below function which appears at first to accomplish the similar operation by using the programming method, really does not. The function receives 2 input arguments: the vector, and an integer with which to compare (therefore it is somewhat more common). It loops through each element in the input vector, and stores the result vector either a 1 or 0 based on whether vec(i) > n is true or false.