Combine two matrices (every other column)
Mostrar comentarios más antiguos
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?
Respuesta aceptada
Más respuestas (2)
Snowfall
el 9 de Feb. de 2016
1 voto
Dillen.A
el 18 de Feb. de 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
4 comentarios
Dillen.A
el 19 de Feb. de 2019
Nice!
Only difference is when you have C={jet(8),cool(7)}; doesn't like it. but appending with nans would solve that.
RAJA SEKHAR BATTU
el 2 de Abr. de 2020
Can we do the same for rows with three matrices to form in to one matrix with alternate rows of the three matrices?
Walter Roberson
el 2 de Abr. de 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.
Categorías
Más información sobre Operators and Elementary Operations en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!