Combine two matrices (every other column)
显示 更早的评论
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?
采纳的回答
更多回答(2 个)
Dillen.A
2019-2-18
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 个评论
Dillen.A
2019-2-19
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
2020-4-2
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
2020-4-2
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.
类别
在 帮助中心 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!