Combine two matrices (every other column)
Afficher commentaires plus anciens
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?
Réponse acceptée
Plus de réponses (2)
Snowfall
le 9 Fév 2016
1 vote
Dillen.A
le 18 Fév 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 commentaires
Dillen.A
le 19 Fév 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
le 2 Avr 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
le 2 Avr 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.
Catégories
En savoir plus sur Operators and Elementary Operations dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!