File Exchange Pick of the Week

Our best user submissions

Multiple-Colon

Sean's pick this week is mcolon by Bruno Luong.

As some of you may know, I spend an unhealthy amount of time on MATLAB Answers browsing through and answering random questions on MathWorks' products. Hey! I'll argue it's healthier than social media or watching the World Cup...

Earlier this week there was a question asking how to most efficiently create a vector from multiple colon subscripts, a common enough task. For example:
% Starting index
startidx = [1 4 pi]

% Stride between each start and ending index
stride = [1 -1 pi]

% Ending index
endidx = [6 0 pi^2]
startidx =
    1.0000    4.0000    3.1416
stride =
    1.0000   -1.0000    3.1416
endidx =
    6.0000         0    9.8696
% Desired result
disp(v)
    1.0000
    2.0000
    3.0000
    4.0000
    5.0000
    6.0000
    4.0000
    3.0000
    2.0000
    1.0000
         0
    3.1416
    6.2832
    9.4248
This can be accomplished with a simple for-loop or some indexing tricks which are sufficiently fast for many applications. However, Bruno's mcolon makes it even faster and more elegant. There are two implementations, one in MATLAB and the other in C++ that can be compiled into a MEX file.

To compile the MEX file, you can call the provided mcolon_install. I really like it when files that need any fancy set up come with their own installation function.

And now the calling syntax:
v = mcolon(startidx,stride,endidx).';
disp(v)
    1.0000
    2.0000
    3.0000
    4.0000
    5.0000
    6.0000
    4.0000
    3.0000
    2.0000
    1.0000
         0
    3.1416
    6.2832
    9.4248

Comments

Do you have a use-case for creating vectors or arrays from multiple subscripts or strides? Give it a try and let us know what you think here or leave a comment for Bruno.

Published with MATLAB® R2014a
|
  • print

Comments

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.