w3resource

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


11. 2D Array F-Order Contiguity

Write a NumPy program that creates a 2D array of shape (3, 3), change its memory layout to 'F' order using asfortranarray(), 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 'F' order
array_f_order = np.asfortranarray(array_2d)

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

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

Output:

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

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 'F' order: We use np.asfortranarray() to ensure the array is stored in column-major ('F') order, resulting in array_f_order.
  • Print the array: We print array_f_order to display the array in 'F' order.
  • Print the strides: We print the strides of array_f_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 check if a 2D array is Fortran contiguous and convert it if it is not, then print its strides.
  • Write a NumPy program to convert a given 2D array to Fortran order using asfortranarray() and compare its strides with the C order version.
  • Write a NumPy program to create a non-fortran contiguous array, then force it into Fortran order and perform an element-wise operation.
  • Write a NumPy program to demonstrate the differences in memory layout by printing the strides of an array before and after using asfortranarray().

Python-Numpy Code Editor:

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

Previous: How to change memory layout of a 2D NumPy array to C order?
Next: How to flatten and reshape a 2D NumPy array?

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.