# HG changeset patch # User Jordi GutiƩrrez Hermoso # Date 1325030797 18000 # Node ID ebe2e6b2ba52cc50ebc75aea3eafad8d41cab978 # Parent acdc4520286a549ecc171c15972c31e7b7799bb6 Start adding vectorization examples diff -r acdc4520286a -r ebe2e6b2ba52 doc/interpreter/vectorize.txi --- a/doc/interpreter/vectorize.txi Tue Dec 27 18:47:18 2011 -0500 +++ b/doc/interpreter/vectorize.txi Tue Dec 27 19:06:37 2011 -0500 @@ -621,5 +621,35 @@ @node Examples @section Examples -Here goes a gallery of vectorization puzzles with solutions culled from -the help mailing list and the machine learning class... +The following are examples of vectorization questions asked by actual +users of Octave and their solutions. + +@c FIXME: We need a lot more examples here. + +@itemize @bullet +@item +For a vector @code{A}, the following loop + +@example +@group +n = length (A); +B = zeros (n, 2); +for i = 1:length(A) + ## this will be two columns, the first is the difference and + ## the second the mean of the two elements used for the diff. + B(i,:) = [A(i+1)-A(i), (A(i+1) + A(i))/2)]; +end +@end group +@end example + +@noindent +can be turned into the following one-liner: + +@example +B = [diff(A)(:), 0.5*(A(1:end-1)+A(2:end))(:)] +@end example + +Note the usage of colon indexing to flatten an intermediate result into +a column vector. This is a common vectorization trick. + +@end itemize