问题描述:

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

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

您可能感兴趣的文章：

- GlassFish Server works on Netbeans 7.2 but not on 7.3
- php - adjust only iframe src from youtube
- ios - How to get the int Value of other class's int variable?(XCode5) I'm confused
- java - GUI update works in IDE but not always from jar file
- ruby on rails - Error: Could not start Passenger Nginx core
- php - Reading a specific line from a text file
- clr - Any implementation of an Unrolled Linked List in C#?
- Finding Hudson Log Files
- Forward to a payment-gateway together with POST data using cURL (or any other PHP server side solution)
- WCF in Winforms app - is it always single-threaded?

随机阅读：

**推荐内容**-

**热点内容**