# Combine two matrices (every other column)

119 views (last 30 days)
Snowfall on 7 Feb 2016
Commented: Walter Roberson on 27 Jan 2021
I have two matrices A and B which are for example
A=[1 2 3;4 5 6; 7 8 9] and B=[10 11 12; 13 14 15; 16 17 18]
And I would like to combine these matrices so that every other column is from A and every other is from B. So the answer should be matrix:
[1 10 2 11 3 12; 4 13 5 14 6 15; 7 16 8 17 9 18]
Of course my matrices are not only 3x3 matrices but n x n matrices.
My history with Matlab is so short that I don't figure out if that is even possible to do?

Walter Roberson on 7 Feb 2016
Provided that A and B have the same number of rows and columns,
AB = reshape([A;B], size(A,1), []);
Walter Roberson on 27 Jan 2021
@Ehsan Asadi I already explained. It is a natural consequence of the fact that MATLAB stores values "down" columns, that for any matrix, the next item in memory after the first row first column is the second row first column then the third row first column, and so on, then then first row second column, second row second column, and so on. That, and the fact that reshape() does not change the order of items in memory and just changes how you refer to them.
A11 A12 A13
A21 A22 A23
is stored in memory as A11 A21 A12 A22 A13 A23 . You can reshape() it to be 3 x 2 and the order in memory would continue to be A11 A21 A12 A22 A13 A23 even though it would now appear to the user as
A11 A22
A21 A13
A12 A23
MATLAB stores (numeric) arrays as blocks of consecutive memory, and indexing is used to compute where to find where in the linear list to look. B(J,K) is found at linear location J + (K-1)*NumberOfRows
If you have used C or C++ you might be wanting to compare how they work. C and C++ store data "across the columns", so in the case of
A11 A12 A13
A21 A22 A23
the order in memory would be A11 A12 A13 A21 A22 A23. But in C or C++ it gets more complicated than that: it does have that way of storing memory but it has another more common way that can be difficult to tell apart.

Snowfall on 9 Feb 2016
Thank you for you both. These worked perfectly in my case.

Dillen.A on 18 Feb 2019
I wanted to "weave" some colourmaps, then I came across this topic. In the end I solved it like this, since I wanted to do it a couple of times.
function out = weave(varargin)
% Example: weave(jet,cool,autumn,spring);
N = numel(varargin);
out = nan(N * max(cellfun(@(s) (size(s, 1)), varargin)), size(varargin{1}, 2));
for ii = 1:N
out(ii:N:size(varargin{ii}, 1) * N - (N - ii), :) = varargin{ii};
end
while all(isnan(out(end, :)))
out(end, :) = [];
end
end
Walter Roberson on 2 Apr 2020
Yes, this user weave function would be happy with any 2D matrices passed in, as long as the matrices all have the same number of columns.