Albert Lazaro de Lara
Albert Lazaro de Lara

Reputation: 2710

Matlab: initialize empty array of matrices

I need to create an empty array of matrices, and after fill it with matrices of the same size.

I have made a little script to explain:

result = [];

for i = 0: 4;
    M = i * ones(5,5); % create matrice
    result = [result,M];  % this would have to append M to results
end

Here result is a matrix of size 5*25 and I need an array of matrices 5*5*4.

I have been researched but I only found this line: result = [result(1),M];

Upvotes: 0

Views: 471

Answers (1)

Suever
Suever

Reputation: 65430

The issue is that [] implicitly concatenates values horizontally (the second dimension). In your case, you want to concatenate them along the third dimension so you could use cat.

result = cat(3, result, M);

But a better way to do it would be to actually pre-allocate your result array using zeros

result = zeros(5, 5, 4);

And then within your loop fill each "slice" of the 3D array with the values.

for k = 0:4
    M = k * ones(5,5);
    result(:,:,k+1) = M;
end

Upvotes: 3

Related Questions