Viktor
Viktor

Reputation: 141

Declaring a multidimensional array in a single statement

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] ] ]

Upvotes: 4

Views: 4758

Answers (2)

gnovice
gnovice

Reputation: 125874

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

Upvotes: 6

Eitan T
Eitan T

Reputation: 32930

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

Upvotes: 6

Related Questions