% dotProduct.m
% Problem is taken from Numerical Analysis+ - Kincaid and Cheney
% p.62, Computer problem 2.2.6
% K. Ming Leung, 01/16/05

clear; format long g;
Xvec = [2.718281828; -3.141592654; 1.414213562; 0.5772156649; 0.3010299957];
Yvec = [  1486.2497;  878366.9879;   -22.37492;  4773714.647;  0.000185049];

% Compute the dot product using MATLAB's function
dotProductMatlab = dot(Xvec,Yvec),

% Compute dot-product in forward order
Product = Xvec .* Yvec, 
dotProductForward= sum(Product),

% Compute dot-product in reverse order
ProductReverse = flipud(Product);
dotProductBackward = sum(ProductReverse),
% Alternatively, use indexing
% faster and more versatile in general
ProductReverse = Product(end:-1:1);
dotProductBackward = sum(ProductReverse),

% sort the product in ascending order
ProductSort = sort(Product);

% Separate out the positive terms from the negative ones
PositiveIndex = (find(ProductSort>=0));
NegativeIndex = (find(ProductSort<0));

PositiveAscending = ProductSort(PositiveIndex); % positive ascending
NegativeAscending = ProductSort(NegativeIndex); % negative ascending

% sum separately the positive and negative terms 
% from large to small magnitudes  
dotProductAscendingMagnitude = sum(PositiveAscending(end:-1:1))+ ...
                                sum(NegativeAscending),

% sum separately the positive and negative terms 
% from large to small magnitudes  
dotProductdescendingMagnitude = sum(PositiveAscending)+sum(NegativeAscending(end:-1:1)),

