% Lecture 11 Script  Ossman
% This script demonstrates multiple different ways of doing the same simple
% task:  Replacing all the negative values in a matrix with zeros.

clear all;
A = randi([-100 100],[10000 5000]);
B = A;    % Pre-allocate space for B
% Note: B = A takes about 1/5 as much time as B = zeros(size(A));

% Method 1:  Use a double loop to index entry by entry through the matrix
% Ask Students why we only check for negative values here

disp('Double Loop Time');
tic()

[Rows Cols] = size(A);
for r = 1:Rows
    for c = 1:Cols
        if A(r,c) < 0
            B(r,c) = 0;
        end
    end
end
toc()

% Method 2: Use a single loop.  Demo this first to show you can single
% index into any matrix
%  >> A = [1 2 3; 4 5 6]
%  A =
%      1     2     3
%      4     5     6
% >> A(:)
% ans =
%      1
%      4
%      2
%      5
%      3
%      6

B = A;
disp('Single Loop Time');
tic()

[Rows Cols] = size(A);
for k = 1:Rows*Cols
    if A(k) < 0
        B(k) = 0;
    end
end
toc()

% Method 3:  Use the find function and Loop

B = A;
disp('Find Function and Loop Time')
tic()

[RowsNeg ColsNeg] = find(A < 0);
for k = 1:length(RowsNeg)
    B(RowsNeg(k),ColsNeg(k)) = 0;
end
toc()

% Method 4:  Use the Find function and single indexing (no loop)

B = A;
disp('Find Function - Single indexing- No Loop Time');
tic()

NegEntries = find(A < 0);
B(NegEntries) = 0;
toc()

% Method 5:  Use the max function

B = zeros(size(A));
disp('Max Function Time');
tic()

B = max(A,B);
toc()





