0

Is there a simple way to create a 3D array in which each layer is initialized with a given 2D array? I could use the following for loop, but it's very slow.

a = rand(1000);
b = zeros(1000, 1000, 1000);
for i = 1:1000
  b(:,:,i) = a;
end
4
  • 1
    try repmat Commented Nov 17, 2022 at 1:22
  • Thank you! repmat(a,1,1,1000) solves the problem! Commented Nov 17, 2022 at 1:55
  • If the goal is actually to initialize your array with random values, you can call rand(1000,1000,1000) Commented Nov 17, 2022 at 8:07
  • @user728826 Just curious, how much faster was repmat? Commented Nov 17, 2022 at 15:56

1 Answer 1

1

You can use repmat or repelem equivalently here

a = rand(10,10);

b = repmat( a, 1, 1, 1000 );
c = repelem( a, 1, 1, 1000 );

You can also use implicit expansion, although it's not as clear to read

d = a + zeros( 1, 1, 1000 );
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.