% logicalIndexing.m
% K. Ming Leung, September 22, 2008

clear;
% Given a vector:
Num = [ 16 9 0 -38 144 -2];
% Suppose we want to replace all the elements that
% are larger than 0 by their square roots,
% and all the other numbers (0 or negative) should
% be increade by 100. How can we do that?

% This returns the indices of all the elements of Num
% that are strictly larger than 0:
PosIdx = find(Num > 0);
disp(Num)   % display the original vector Num
% Replace all those elements by their square roots:
Num(PosIdx) = sqrt(Num(PosIdx));
% Find the indices of the element of Num that
% are less than or equal to 0:
NegIdx = find(Num <= 0);
% Increase those elements by 100
Num(NegIdx) = Num(NegIdx) + 100;
disp(Num)  % display the new vector Num

% Another way (perhaps quicker) to perform the above
% task using logical indexing:

% Recall the original vector:
Num = [ 16 9 0 -38 144 -2];
% Create a logical vector for the positive elements:
LogicPositive = Num > 0;
% 
disp('Replace positive elements by their square roots');
Num(LogicPositive) = sqrt(Num(LogicPositive)),
% Use ~LogicPositive for the non-positive elements 
% Recall: ~ is the operator for logical negation:
% true becomes false and false becomes true.
disp('Increase all non-positive numbers by 100:');
Num(~LogicPositive) = Num(~LogicPositive) + 100