[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) = [];






Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s