Loren on the Art of MATLAB

Turn ideas into MATLAB

Sort of Find a Solution

Posted by Loren Shure,

In MATLAB 7, Release 14, we enhanced two useful and often used functions, sort and find in part because we noticed some common coding patterns in our MATLAB code and customers'. With the older patterns we found, we felt we could create new options in these functions that would encourage more readable programs that generally performed better as well. It's worth noting that mlint knows to look for these older patterns and suggest that users replace their code with the newer constructs.

sort Code Pattern

Sometimes algorithms require a list be sorted in a descending direction but the original implementation of sort only produced an ascending list. For just about the same effort as the original function, the enhanced sort functionality allows you to sort your array in the descending direction without requiring the creation of an intermediate array that is sorted in the ascending direction.

Preferred

Adesc = sort(A,'descend'); % requires MATLAB 7 syntax

Not Recommended

Adesc = flipud(sort(A));

find Code Pattern

Often when searching for some condition in an array, we need to either locate a fixed number of occurrences or determine if there are any at all. These ideas can be expressed clearly with the enhancements to find in MATLAB 7. Instead of scanning the entire array to determine if there's at least one instance, we can stop searching as soon as one instance is found. The code is still very readable, perhaps more so, and, on average for random data, more efficient.

Preferred

x = rand(1,100);
% find 3 occurrences, using MATLAB 7 syntax
n = 3;
xTrue = find(x>.5, n);  % length(xTrue) might be less than n

% check for presence of condition,
% scanning until the first occurrence
if ~isempty(find(x>.5),1)  
     doSomething;
end
 

Not Recommended

x = rand(1,100);
% find 3 occurrences
n = 3;
xTrue = find(x>.5);
xTrue(n+1:end) = [];

% check for presence of condition,
% by scanning entire array
if ~isempty(find(x>.5))  % OR any(any(x))
     doSomething;
end

Benefits

  • Time and memory efficiency
  • Don't allocate potientially large temporary arrays and then throw pieces away
  • find stops once enough entities are found rather than scanning the entire array

Note

Comments are closed.