Ravel and UnRavel: Difference between revisions
From Master of Neuroscience Wiki
Created page with " == Top == Questions to [mailto:davrot@uni-bremen.de David Rotermund] == [https://numpy.org/doc/stable/reference/generated/numpy.ravel_multi_index.html numpy.ravel_multi_index] == <syntaxhighlight lang="python">numpy.ravel_multi_index(multi_index, dims, mode='raise', order='C')</syntaxhighlight><blockquote>Converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index.</blockquote><syntaxhighlight lang="python">import numpy as..." |
No edit summary |
||
| Line 1: | Line 1: | ||
Questions to [mailto:davrot@uni-bremen.de David Rotermund] | Questions to [mailto:davrot@uni-bremen.de David Rotermund] | ||
Latest revision as of 16:42, 17 October 2025
Questions to David Rotermund
numpy.ravel_multi_index
numpy.ravel_multi_index(multi_index, dims, mode='raise', order='C')
Converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index.
import numpy as np
idx = np.ravel_multi_index(([0, 1, 2], [0, 1, 1]), dims=(3, 2))
print(idx) # -> [0 3 5]
a = np.zeros((3, 2))
a.flat[idx] = 1
print(a)
print()
a = np.zeros((3, 2))
a.flat[idx] = np.arange(1, idx.shape[0] + 1)
print(a)
Output:
[[1. 0.]
[0. 1.]
[0. 1.]]
[[1. 0.]
[0. 2.]
[0. 3.]]
numpy.unravel_index
numpy.unravel_index(indices, shape, order='C')
Converts a flat index or array of flat indices into a tuple of coordinate arrays.
import numpy as np
idx = np.ravel_multi_index(([0, 1, 2], [0, 1, 1]), dims=(3, 2))
print(idx) # -> [0 3 5]
a, b = np.unravel_index(idx, shape=(3, 2))
print(a) # -> [0 1 2]
print(b) # -> [0 1 1]