0

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

1
  • 1
    Maybe just a typo, but do you not want result = [result,M];. But I guess there might be other problem in terms of dimensions. Commented Dec 3, 2016 at 17:16

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

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.