File Exchange

image thumbnail

interleave

version 1.0.0.0 (987 Bytes) by Jason Blackaby
Interleave two vectors

4 Downloads

Updated 18 Oct 2007

No License

This function simply interleaves two vectors. The vectors can be of different lengths. If one vector is longer, the leftover elements are just appended to the output vector. This can be done in a couple of lines if the vector lengths are known, but this function handles most of the possibilities automatically, and should save a few minutes.

Example:
z = interleave([1 2 3 4], [5 6 7 8 9 10])
= 1 5 2 6 3 7 4 8 9 10

Cite As

Jason Blackaby (2021). interleave (https://www.mathworks.com/matlabcentral/fileexchange/16919-interleave), MATLAB Central File Exchange. Retrieved .

Comments and Ratings (4)

Yi Cao

Another way to do it is
...
r=cell(2,max(numel(x),numel(y)));
r(1,1:numel(x))=num2cell(x);
r(2,1:numel(y))=num2cell(y);
r=[r{:}];
...

Jason Blackaby

Thanks for the comments. I never thought of doing it the way Urs did, but then again, I am not too familiar with cell arrays. It's a lot more elegant.

urs (us) schwarz

i agree with john, albeit the author might consider a slightly different approach for the engine, which works even if one or both inputs is/are []:

function r=ilv(x,y)
% a few error checks...
xc=num2cell(x);
yc=num2cell(y);
r=cell(1,numel(x)+numel(y));
r(1:2:2*numel(x))=xc;
r(2:2:2*numel(y))=yc;
r=[r{:}];
% a final row/col-vec check

just a thought
us

John D'Errico

I like this code, alhough I'll admit I've never had a need for what it does. It fills a niche in Matlab.

Its well written, internally commented, good error checking, good help, an H1 line, an example of use, no mlint flags, and it is vectorized. I can't ask for much more.

Only one comment. The code returns an error if either x or y is empty. But why not just return y if x is empty, or x if y is empty? This would seem to be consistent and appropriate.

MATLAB Release Compatibility
Created with R2007a
Compatible with any release
Platform Compatibility
Windows macOS Linux
Acknowledgements

Inspired: Interleave Vectors or Matrices

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!