Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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] ] ]
like image 253
Viktor Avatar asked Dec 17 '22 16:12

Viktor


2 Answers

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

like image 124
Eitan T Avatar answered Feb 04 '23 10:02

Eitan T


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
like image 32
gnovice Avatar answered Feb 04 '23 10:02

gnovice