Do you ever need both the minimum and maximum values on the same data? Sometimes I do, for example, when I want to tweak the limits of a 2-dimensional plot. So I was wondering whether that is a common task? I also wondered what the overhead is in calling min and max separately, instead of scanning through the data once, looking for both the lowest and highest values.
I will explore this idea by creating my own simplified versions of max and min, working only for real vector inputs, not checking for NaNs, and not doing any error checking. Clearly, the code I show is not meant for production but to get to the heart of the algorithm.
Here I create a very small test dataset.
n = 10; x = rand(n,1)
x = 0.9145 0.1215 0.3765 0.7912 0.1848 0.0508 0.5562 0.4633 0.8539 0.0384
This function is simple, as advertized.
function xmin = mymin(x) %MYMIN Minimum value of real vector input. % MYMIN is a simplified version of MIN that % finds the minimum value for % real-valued vector. NaNs are not treated. xmin = Inf; for ind = 1:length(x) if x(ind) < xmin xmin = x(ind); end end
Now I compare the result from mymin to the built-in min function in MATLAB.
xmin = mymin(x); xminML = min(x); tf = isequal(xmin, xminML)
tf = 1
Do similar testing with mymax.
xmax = mymax(x); xmaxML = max(x); tf = isequal(xmax, xmaxML)
tf = 1
Now I want to do some timing so I will create a much larger array of data.
n = 3e7; xL = rand(n,1); tic xLmin = mymin(xL); timeMin = toc tic xLmax = mymax(xL); timeMax = toc
timeMin = 0.7469 timeMax = 0.7491
Now let me show you my combined function myminmax that loops through the data the same way mymin and mymax did, but does both calculations in the loop together.
function [xmin, xmax] = myminmax(x) %MYMINMAX Extreme values of real vector input. % MYMINMAX is a simplified version of MIN and % MAX combined and finds the % minimum and maximum values for real-valued vector. % NaNs are not treated. xmin = Inf; xmax = -Inf; for ind = 1:length(x) if x(ind) < xmin xmin = x(ind); end if x(ind) > xmax xmax = x(ind); end end
First, let's check that we get the expected results.
[xminNew, xmaxNew] = myminmax(x); tf = isequal([xminNew xmaxNew], [xmin xmax])
tf = 1
And now let's time the combined function.
tic [xLminNew xLmaxNew] = myminmax(xL); timeMinmax = toc
timeMinmax = 1.0614
To compare the times, let's look at the sum for the times calling the individual functions vs. calling the combined one.
t2 = timeMin+timeMax; format long disp('Adding separate times Combined Time') disp([t2 timeMinmax])
Adding separate times Combined Time 1.495988735998570 1.061442445897453
Reset format to default
Is it worth having a combined function for min and max from a speed point of view? I don't know. It depends on many things, including how often it's needed, and if finding the min and max values is one of the dominant time consumers in the overall algorithm.
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.