w3resource

How to change memory layout of a 2D NumPy array to C order?


10. 2D Array C-Order Contiguity

Write a NumPy program that creates a 2D array of shape (3, 3), change its memory layout to 'C' order using ascontiguousarray(), and print the array and its strides.

Sample Solution:

Python Code:

import numpy as np

# Create a 2D array of shape (3, 3)
array_2d = np.array([[1, 2, 3],
                     [4, 5, 6],
                     [7, 8, 9]])

# Change the memory layout to 'C' order
array_c_order = np.ascontiguousarray(array_2d)

# Print the array in 'C' order
print("Array in 'C' order:\n", array_c_order)

# Print the strides of the array in 'C' order
print("Strides of the array in 'C' order:", array_c_order.strides)

Output:

Array in 'C' order:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]
Strides of the array in 'C' order: (12, 4)

Explanation:

  • Import NumPy library: We start by importing the NumPy library to handle array operations.
  • Create a 2D array: We create a 2D array array_2d of shape (3, 3) using np.array().
  • Change memory layout to 'C' order: We use np.ascontiguousarray() to ensure the array is stored in row-major ('C') order, resulting in array_c_order.
  • Print the array: We print array_c_order to display the array in 'C' order.
  • Print the strides: We print the strides of array_c_order using the strides attribute to show the number of bytes to step in each dimension when traversing the array.

For more Practice: Solve these Related Problems:

  • Write a NumPy program to convert a non-contiguous 2D array into a C-contiguous array using ascontiguousarray() and print its flags and strides.
  • Write a NumPy program to compare the strides of a 2D array before and after converting it to C order.
  • Write a NumPy program to check an array's contiguity and, if needed, convert it to C order and verify the change.
  • Write a NumPy program to create a sliced 2D array that is non-contiguous, then use ascontiguousarray() to make it contiguous and print the new strides.

Go to:


Previous: How to reshape and modify a 1D NumPy array to a 3x3 matrix?
Next: How to change memory layout of a 2D NumPy array to F order?

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.