An alternative way to directly access the 2D array without making a transformed copy is to use the integer division and the modulo operators.
import numpy as np
# example array
rect_arr = np.array([[1, 2, 3, 10], [4, 5, 6, 11], [7, 8, 9, 12]])
rows, cols = rect_arr.shape
print("Array is:\n", rect_arr)
print(f"rows = {rows}, cols = {cols}")
# Access by Linear Indexing
# Reference:
# https://upload.wikimedia.org/wikipedia/commons/4/4d/Row_and_column_major_order.svg
total_elems = rect_arr.size
# Row major order
print("\nRow Major Sequence:")
for linear_index in range(total_elems):
# do something with rect_arr[linear_index // cols][linear_index % cols]
# Sequence will be 1, 2, 3, 10, 4, 5, 6, 11, 7, 8, 9, 12
print(rect_arr[linear_index // cols][linear_index % cols])
# Columnn major order
print("\nColumn Major Sequence:")
for linear_index in range(total_elems):
# do something with rect_arr[linear_index % rows][linear_index // rows]
# Sequence will be 1, 4, 7, 2, 5, 8, 3, 6, 9, 10, 11, 12
print(rect_arr[linear_index % rows][linear_index // rows])
# With unravel_index
# Row major order
row_indices = range(total_elems)
row_transformed_arr = rect_arr[np.unravel_index(row_indices, rect_arr.shape, "C")]
print(row_transformed_arr)
# Columnn major order
col_indices = range(total_elems)
col_transformed_arr = rect_arr[np.unravel_index(row_indices, rect_arr.shape, "F")]
print(col_transformed_arr)
Useful for plotting in subplots:
# <df> is a date-indexed dataframe with 8 columns containing time-series data
fig, axs = plt.subplots(nrows=4, ncols=2)
rows, cols = axs.shape
# Order plots in row-major
for i, colname in enumerate(df):
df[colname].plot(ax=axs[i // cols][i % cols], title=colname)
plt.show()
# Order plots in column-major
for i, colname in enumerate(df):
df[colname].plot(ax=axs[i % rows][i // rows], title=colname)
plt.show()
x(1:5)simply takes the first five elements in column-major order, which you can think of like how you described, but MATLAB doesn't make the in-between step.