Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: How can I merge 2 arrays?
Date: Tue, 28 Sep 2010 11:14:05 +0000 (UTC)
Organization: Erasmus MC
Lines: 40
Message-ID: <i7silt$171$1@fred.mathworks.com>
References: <i7sadh$6nf$1@fred.mathworks.com> <i7sfo4$l7b$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-05-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1285672445 1249 172.30.248.35 (28 Sep 2010 11:14:05 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Tue, 28 Sep 2010 11:14:05 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 870065
Xref: news.mathworks.com comp.soft-sys.matlab:673843

"Terry " <xterry.xnycum@xgmail.no-xs.com> wrote in message <i7sfo4$l7b$1@fred.mathworks.com>...
> "James Ramm" <james@whitehocott.plus.com> wrote in message <i7sadh$6nf$1@fred.mathworks.com>...
> > Hi
> > I have 2 MxN arrays of frequency and voltage data.
> > I would like to merge them to give a M-by-2N array of alternating freq and voltage columns, i.e:
> > 
> > Freq1 Voltage1 Freq2 Voltage2 Freq3 Voltage3........FreqN VoltageN
> > 
> > 
> > I also need to be able to do it in a dynamic routine - one that can work for any M-by-N array pairs. 
> > I have no idea how to do this - can anyone help?
> 
> fCols = 1:2:2*N-1;  % aka odds
> vCols = 2:2:2*N;    % aka evens
> fv = zeros(M,2*N);
> fv(:,fCols) = f;
> fv(:,vCols) = v;
> 
> ...which you might consolidate and add an assertion to to get this:
> [M N] = size(f);
> assert(all([M N]==size(v)));
> fv = zeros(M,2*N);
> fv(:,1:2:2*N-1) = f;
> fv(:,2:2:2*N) = v;
> 
> The larger M and/or N are, the more likely this method is to be faster than one involving reshaping, I believe.
> 
> Terry

A more concise approach along the same lines:

% some test data
  f = repmat(1:5,3,1)
  v = 10* f
% engine
  ix = 2*(1:size(f,2))
  fv(:,[ix-1 ix]) = [f v] % build final matrix in one step

hth
Jos