当前位置: 动力学知识库 > 问答 > 编程问答 >

matrix - Matlab Combining matrices

问题描述:

I have a 1024x3x3 matrix A and another of same dimensions B. I want to make a matrix that is 1024x2x3x3 that is a combination of the two, can somebody help? My matlab skills suck.

网友答案:

A one line solution to your problem is this:

D = permute(cat(4, A, B), [1 4 2 3]);

However, this needs some explaining. Here is an example to get us started:

%# A 3-d pre-allocation example
A = rand(3, 3, 3);
B = rand(3, 3, 3);
D = NaN(3, 3, 3, 2);
D(:, :, :, 1) = A;
D(:, :, :, 2) = B;

The problem is conceptually much more straightforward if you begin by pre-allocating the output matrix you want, and then manually allocate the input matrices to the output matrix. However, once you've grasped this concept, you can use one call to the cat function to solve the problem:

%# The 3-d cat solution
A = rand(3, 3, 3);
B = rand(3, 3, 3);
D = cat(4, A, B);

The first argument of cat provides the dimension you want to concatenate along. By choosing a dimension that is one greater than the current maximum dimension of our matrix, we create a new dimension and concatenate along it.

So, this solves the problem if what we want to do is add a new dimension at the end of our current set of dimensions. However, in the question, you state that you want the new dimension to appear as the second index. A simple extension of the pre-allocation example that accomodates this is:

%# Another 3-d pre-allocation example
A = rand(3, 3, 3);
B = rand(3, 3, 3);
D = NaN(3, 2, 3, 3);
D(:, 1, :, :) = A;
D(:, 2, :, :) = B;

But perhaps a better method that doesn't involve explicit allocation is to use the trick with cat to create an extra dimension, and then use permute to re-arrange the dimensions into the order we want, eg:

%# Another 3-d example with cat and permute
A = rand(3, 3, 3);
B = rand(3, 3, 3);
D = cat(4, A, B);
D = permute(D, [1 4 2 3]);

Hope this helps. Cheers.

网友答案:

Concatenate A and B and use reshape to change the dimensions of the resulting matrix:

C = reshape([A; B],1024,2,3,3);
网友答案:

You can do:

Given: A -> 1024 x 3 x 3 B -> 1024 x 3 x 3

Choose your option:

1) C = [A B]; %-> 1024 x 6 x 3

2) C = [A ; B]; %-> 2048 x 3 x 3

3) C = zeros(1024,3,3,2);

C(:,:,:,1) = A;

C(:,:,:,2) = B;

%C -> 1024 x 3 x 3 x 2

分享给朋友:
您可能感兴趣的文章:
随机阅读: