[MATLAB] Dot Operation – No More For Loop!

MATLAB is a matrix based software that is widely used in engineering. Since the software is matrix based, it is actually a lot faster to do matrix operations rather than looping.

The following is an example of how to create a filter to eliminate all non-positive numbers from an array using the dot operation instead of a for loop.


function y = negative_filter( x )
%=========================================================================
% function y = negative_filter( x )
% plugging in a matrix will return only the positive numbers in a vector
%=========================================================================

%Create a zero matrix same size as the incoming matrix for comparison
z = zeros( size(x));

%Create a "filter" matrix that return 1 if the condition is true
%It will return 0 if the condition is false
filter = (x > z);

%This function multply the "filter matrix" with the incoming matrix
%elements by elements, note the '.' in front of '*'. This line will set all
%number less than 0, or false to the earlier stated condition to 0.
y = filter .* x;

%This remove all zero terms from the matrix
y(y==0) = [];