Concatenate vectors of unequal lengths
Brett's Pick this week is padcat, by Jos--one of the File Exchange's most popular contributors.
MATLAB has a few containers that are useful for storing heterogeneous data. In particular, one can store just about any combination of variables or data types in cell arrays, structures, or (if you have the always useful Statistics Toolbox) dataset arrays. Sometimes you want something lighter-weight, and easy to manipulate. If you just wanted to combine several row or column vectors into a matrix, the function cat makes short work of it, if the vectors are the same length and orientation (all row vectors or all column vectors). If, on the other hand, they had the same orientation but different lengths, cat wouldn't know what to do with them.
With padcat, you could automatically combine them, padding shorter vectors with NaNs as necessary.
Say, for example, that you had four row vectors of different length:
a = 1:5 ; b = 1:3 ; c = [] ; d = 1:4 ;
and you wanted to create from them a single matrix. Try padcat:
M = padcat(a,b,c,d) % all are row vectors
M = 1 2 3 4 5 1 2 3 NaN NaN NaN NaN NaN NaN NaN 1 2 3 4 NaN
As an added bonus, Jos's function can generate a second output that contains a binary mask showing true (or 1) where elements of M originated from an input vector, and false (or 0) where they were padded. This can be useful if any of the component vectors themselves contain NaNs. For instance:
a = [1:3]' ; b = [] ; c = [1;NaN] ;
[M,tf] = padcat(a,b,c) % all are column vectors
M = 1 NaN 1 2 NaN NaN 3 NaN NaN tf = 1 0 1 1 0 1 1 0 0
(Note that the second element in the third column of tf [i.e., row 2, column 3] is 1, indicating that the NaN in that position of M originated in vector c.)
Just a nice utility function to have around. Thanks, Jos!
- Category:
- Picks
Comments
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.