4

Let's say I want to create a matrix A with dimensions 3×4×4 with a single statement (i.e one equality, without any concatenations), something like this:

%// This is one continuous row
A = [ [ [3 3 4 4], [8 11 8 7], [4 4 6 7], [4 7 6 6] ];  ...
      [ [3 2 4 2], [9 6 4 12], [4 3 3 4], [5 10 7 3] ]; ...
      [ [2 2 1 2], [3 3 3 2], [2 2 2 2],  [3 3 3 3] ] ]

2 Answers 2

6

You can use cat to "layer" 2-D matrices along the third dimension, for example:

A = cat(3, ones(4), 2*ones(4), 3*ones(4));

Technically this is concatenation, but it's still only one assignment.

CATLAB

Sign up to request clarification or add additional context in comments.

Comments

6

The concatenation operator [] will only work in 2 dimensions, like [a b] to concatenate horizontally or [a; b] to concatenate vertically. To create matrices with higher dimensions you can use the reshape function, or initialize a matrix of the size you want and then fill it with your values. For example, you could do this:

A = reshape([...], [3 4 4]);  % Where "..." is what you have above

Or this:

A = zeros(3, 4, 4);  % Preallocate the matrix
A(:) = [...];        % Where "..." is what you have above

1 Comment

The second one is what I did. Thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.