Combine two matrices (every other column)
Ältere Kommentare anzeigen
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?
Akzeptierte Antwort
Weitere Antworten (2)
Snowfall
am 9 Feb. 2016
1 Stimme
Dillen.A
am 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
4 Kommentare
Dillen.A
am 19 Feb. 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
am 2 Apr. 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
am 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.
Kategorien
Mehr zu Logical finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!