Expand
Contents
Background
Matt Fig is one of MATLAB Central's top contributors. Even though he's been on hiatus for over two years, he's still the 10th highest contributor on Answers and the 14th most downloaded author on the File Exchange.
Expand
My pick today is a contribution of Matt's that made an appearance somewhere in the code base for my Master's thesis. I was working with large 3-dimensional CT images and computation speed was important. Here's what it does:
x = magic(3) xexpanded = expand(x,[3 2])
x = 8 1 6 3 5 7 4 9 2 xexpanded = 8 8 1 1 6 6 8 8 1 1 6 6 8 8 1 1 6 6 3 3 5 5 7 7 3 3 5 5 7 7 3 3 5 5 7 7 4 4 9 9 2 2 4 4 9 9 2 2 4 4 9 9 2 2
As you can see x has been expanded thrice along rows and twice along columns ([3 2]). Expand also works along N-dimensional arrays but does have a limitation that the expansion must match the number of dimensions. This can be circumvented with a second call to repmat to expand along higher dimensions.
Kron
The 2-dimensional expand operation has always been possible with kron, but it requires creating a ones matrix and, at least back in my grad school era, was slower than expand. Since I was working with 3-dimensional images, this was not an option.
xkron = kron(x,ones(3,2))
xkron = 8 8 1 1 6 6 8 8 1 1 6 6 8 8 1 1 6 6 3 3 5 5 7 7 3 3 5 5 7 7 3 3 5 5 7 7 4 4 9 9 2 2 4 4 9 9 2 2 4 4 9 9 2 2
R2015a Introduces repelem
Starting in R2015a, which shipped the first week of March, there is a new function that does the same thing as expand and more built in to MATLAB: meet repelem.
xrep = repelem(x,3,2)
xrep = 8 8 1 1 6 6 8 8 1 1 6 6 8 8 1 1 6 6 3 3 5 5 7 7 3 3 5 5 7 7 3 3 5 5 7 7 4 4 9 9 2 2 4 4 9 9 2 2 4 4 9 9 2 2
And into three dimensions:
xrep3 = repelem(x,3,1,2)
xrep3(:,:,1) = 8 1 6 8 1 6 8 1 6 3 5 7 3 5 7 3 5 7 4 9 2 4 9 2 4 9 2 xrep3(:,:,2) = 8 1 6 8 1 6 8 1 6 3 5 7 3 5 7 3 5 7 4 9 2 4 9 2 4 9 2
repelem on a vector can also vary the number of repeats, very nice for building up a vector or run length encoding.
v123 = repelem([2 4 7],1:3)
v123 = 2 4 4 7 7 7
R2015a Other
Browsing through the release notes for R2015a and having had the opportunity to beat on the R2015a Prerelease, here are a few of my other favorite new features:
- discretize - similar to histcounts or histc but skips the histogram counting part.
- Array Size Limitation - Helps accidentally creating large arrays that would cause you to run out of RAM.
- Tab Complete for Object Authoring - Finally!
- ismembertol and uniquetol - ismember and unique with tolerance; these will save me a few calls to discretize.
Comments
Thanks Matt for providing the expand functionality; it has been very useful for nearly 6 years!
Give expand, repelem, and R2015a a try and let us know what you think about any of them here or leave a comment for Matt.
댓글
댓글을 남기려면 링크 를 클릭하여 MathWorks 계정에 로그인하거나 계정을 새로 만드십시오.