0
# Array Operations
1
2
Core array creation functions and array manipulation operations that mirror NumPy's interface but operate on GPU memory. These functions provide the foundation for all GPU-accelerated computations in CuPy.
3
4
## Capabilities
5
6
### Array Creation - Basic
7
8
Create arrays with specific patterns or values, all stored in GPU memory for immediate use in GPU computations.
9
10
```python { .api }
11
def array(obj, dtype=None, copy=True, order='K', subok=False, ndmin=0):
12
"""Create array from array-like object in GPU memory.
13
14
Parameters:
15
- obj: array-like, input object to convert
16
- dtype: data type for the array
17
- copy: bool, whether to copy data
18
- order: memory layout order ('C', 'F', 'A', 'K')
19
- subok: bool, whether to return subclass
20
- ndmin: int, minimum number of dimensions
21
22
Returns:
23
cupy.ndarray: Array in GPU memory
24
"""
25
26
def zeros(shape, dtype=float64, order='C'):
27
"""Create array filled with zeros.
28
29
Parameters:
30
- shape: int or sequence of ints, shape of array
31
- dtype: data type
32
- order: memory layout order
33
34
Returns:
35
cupy.ndarray: Array of zeros
36
"""
37
38
def ones(shape, dtype=None, order='C'):
39
"""Create array filled with ones.
40
41
Parameters:
42
- shape: int or sequence of ints, shape of array
43
- dtype: data type
44
- order: memory layout order
45
46
Returns:
47
cupy.ndarray: Array of ones
48
"""
49
50
def empty(shape, dtype=float64, order='C'):
51
"""Create uninitialized array.
52
53
Parameters:
54
- shape: int or sequence of ints, shape of array
55
- dtype: data type
56
- order: memory layout order
57
58
Returns:
59
cupy.ndarray: Uninitialized array
60
"""
61
62
def full(shape, fill_value, dtype=None, order='C'):
63
"""Create array filled with specified value.
64
65
Parameters:
66
- shape: int or sequence of ints, shape of array
67
- fill_value: scalar, value to fill array with
68
- dtype: data type
69
- order: memory layout order
70
71
Returns:
72
cupy.ndarray: Array filled with fill_value
73
"""
74
```
75
76
### Array Creation - From Existing Arrays
77
78
Create new arrays based on the shape and properties of existing arrays.
79
80
```python { .api }
81
def zeros_like(a, dtype=None, order='K', subok=True, shape=None):
82
"""Create array of zeros with same shape as existing array.
83
84
Parameters:
85
- a: array-like, array whose shape to copy
86
- dtype: data type, defaults to a.dtype
87
- order: memory layout order
88
- subok: bool, whether to return subclass
89
- shape: int or sequence of ints, override shape
90
91
Returns:
92
cupy.ndarray: Array of zeros with same shape as a
93
"""
94
95
def ones_like(a, dtype=None, order='K', subok=True, shape=None):
96
"""Create array of ones with same shape as existing array."""
97
98
def empty_like(a, dtype=None, order='K', subok=True, shape=None):
99
"""Create uninitialized array with same shape as existing array."""
100
101
def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None):
102
"""Create filled array with same shape as existing array."""
103
```
104
105
### Array Creation - Ranges and Sequences
106
107
Generate arrays with evenly spaced values or specific patterns.
108
109
```python { .api }
110
def arange(start, stop=None, step=1, dtype=None):
111
"""Create array with evenly spaced values within interval.
112
113
Parameters:
114
- start: number, start of interval
115
- stop: number, end of interval (exclusive)
116
- step: number, spacing between values
117
- dtype: data type
118
119
Returns:
120
cupy.ndarray: Array of evenly spaced values
121
"""
122
123
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0):
124
"""Create array with evenly spaced values over specified interval.
125
126
Parameters:
127
- start: scalar, start value
128
- stop: scalar, stop value
129
- num: int, number of samples
130
- endpoint: bool, whether to include stop value
131
- retstep: bool, whether to return spacing
132
- dtype: data type
133
- axis: int, axis along which to store samples
134
135
Returns:
136
cupy.ndarray: Array of evenly spaced samples
137
tuple: If retstep is True, (samples, step)
138
"""
139
140
def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):
141
"""Create array with logarithmically spaced values."""
142
143
def meshgrid(*xi, indexing='xy', sparse=False, copy=True):
144
"""Create coordinate matrices from coordinate vectors."""
145
```
146
147
### Array Creation - Special Matrices
148
149
Create arrays with specific mathematical structures.
150
151
```python { .api }
152
def eye(N, M=None, k=0, dtype=float64, order='C'):
153
"""Create 2-D array with ones on diagonal and zeros elsewhere.
154
155
Parameters:
156
- N: int, number of rows
157
- M: int, number of columns (defaults to N)
158
- k: int, diagonal offset
159
- dtype: data type
160
- order: memory layout order
161
162
Returns:
163
cupy.ndarray: Identity-like matrix
164
"""
165
166
def identity(n, dtype=None):
167
"""Create identity matrix."""
168
169
def diag(v, k=0):
170
"""Extract diagonal or construct diagonal array."""
171
172
def tri(N, M=None, k=0, dtype=float64):
173
"""Create array with ones at and below given diagonal."""
174
```
175
176
### Shape Manipulation
177
178
Modify array shapes without changing the underlying data.
179
180
```python { .api }
181
def reshape(a, newshape, order='C'):
182
"""Give new shape to array without changing data.
183
184
Parameters:
185
- a: array-like, input array
186
- newshape: int or tuple of ints, new shape
187
- order: memory layout order
188
189
Returns:
190
cupy.ndarray: Reshaped array
191
"""
192
193
def ravel(a, order='C'):
194
"""Return flattened array."""
195
196
def flatten(a, order='C'):
197
"""Return copy of array collapsed to one dimension."""
198
199
def squeeze(a, axis=None):
200
"""Remove single-dimensional entries from shape."""
201
202
def expand_dims(a, axis):
203
"""Expand dimensions of array."""
204
```
205
206
### Array Joining
207
208
Combine multiple arrays into single arrays.
209
210
```python { .api }
211
def concatenate(arrays, axis=0, out=None):
212
"""Join arrays along existing axis.
213
214
Parameters:
215
- arrays: sequence of arrays, arrays to join
216
- axis: int, axis along which to join
217
- out: ndarray, destination array
218
219
Returns:
220
cupy.ndarray: Concatenated array
221
"""
222
223
def stack(arrays, axis=0, out=None):
224
"""Join arrays along new axis."""
225
226
def vstack(tup):
227
"""Stack arrays vertically (row-wise)."""
228
229
def hstack(tup):
230
"""Stack arrays horizontally (column-wise)."""
231
232
def dstack(tup):
233
"""Stack arrays depth-wise (along third axis)."""
234
235
def column_stack(tup):
236
"""Stack 1-D arrays as columns into 2-D array."""
237
```
238
239
### Array Splitting
240
241
Split single arrays into multiple sub-arrays.
242
243
```python { .api }
244
def split(ary, indices_or_sections, axis=0):
245
"""Split array into multiple sub-arrays.
246
247
Parameters:
248
- ary: ndarray, input array to split
249
- indices_or_sections: int or 1-D array, split points
250
- axis: int, axis along which to split
251
252
Returns:
253
list: List of sub-arrays
254
"""
255
256
def array_split(ary, indices_or_sections, axis=0):
257
"""Split array into multiple sub-arrays (allows unequal division)."""
258
259
def hsplit(ary, indices_or_sections):
260
"""Split array horizontally (along columns)."""
261
262
def vsplit(ary, indices_or_sections):
263
"""Split array vertically (along rows)."""
264
265
def dsplit(ary, indices_or_sections):
266
"""Split array along third axis."""
267
```
268
269
### Array Transposition
270
271
Rearrange array dimensions and transpose operations.
272
273
```python { .api }
274
def transpose(a, axes=None):
275
"""Permute dimensions of array.
276
277
Parameters:
278
- a: array-like, input array
279
- axes: list of ints, permutation of dimensions
280
281
Returns:
282
cupy.ndarray: Transposed array
283
"""
284
285
def swapaxes(a, axis1, axis2):
286
"""Interchange two axes of array."""
287
288
def moveaxis(a, source, destination):
289
"""Move axes of array to new positions."""
290
291
def rollaxis(a, axis, start=0):
292
"""Roll specified axis backwards."""
293
```
294
295
### Array Tiling and Repetition
296
297
Repeat and tile array elements or entire arrays.
298
299
```python { .api }
300
def tile(A, reps):
301
"""Construct array by repeating A given number of times.
302
303
Parameters:
304
- A: array-like, input array
305
- reps: int or sequence of ints, repetitions along each axis
306
307
Returns:
308
cupy.ndarray: Tiled array
309
"""
310
311
def repeat(a, repeats, axis=None):
312
"""Repeat elements of array.
313
314
Parameters:
315
- a: array-like, input array
316
- repeats: int or array of ints, repetitions for each element
317
- axis: int, axis along which to repeat
318
319
Returns:
320
cupy.ndarray: Array with repeated elements
321
"""
322
```
323
324
### Array Rearrangement
325
326
Flip, roll, and rotate array elements.
327
328
```python { .api }
329
def flip(m, axis=None):
330
"""Reverse order of elements in array along axis."""
331
332
def fliplr(m):
333
"""Flip array left to right."""
334
335
def flipud(m):
336
"""Flip array up to down."""
337
338
def roll(a, shift, axis=None):
339
"""Roll array elements along axis."""
340
341
def rot90(m, k=1, axes=(0, 1)):
342
"""Rotate array 90 degrees in plane specified by axes."""
343
```
344
345
## Usage Examples
346
347
### Basic Array Creation
348
349
```python
350
import cupy as cp
351
352
# Create arrays of different types
353
zeros_arr = cp.zeros((3, 4))
354
ones_arr = cp.ones((2, 3), dtype=cp.int32)
355
random_arr = cp.random.random((5, 5))
356
357
# Create from Python lists
358
data = [[1, 2, 3], [4, 5, 6]]
359
gpu_array = cp.array(data)
360
361
# Create ranges
362
sequence = cp.arange(0, 10, 0.5)
363
linear = cp.linspace(0, 1, 100)
364
```
365
366
### Shape Manipulation
367
368
```python
369
import cupy as cp
370
371
# Create and reshape arrays
372
original = cp.arange(12)
373
reshaped = cp.reshape(original, (3, 4))
374
flattened = cp.ravel(reshaped)
375
376
# Add and remove dimensions
377
expanded = cp.expand_dims(reshaped, axis=2) # Shape: (3, 4, 1)
378
squeezed = cp.squeeze(expanded) # Shape: (3, 4)
379
```
380
381
### Array Concatenation
382
383
```python
384
import cupy as cp
385
386
# Create sample arrays
387
a = cp.array([[1, 2], [3, 4]])
388
b = cp.array([[5, 6], [7, 8]])
389
390
# Join along different axes
391
vertical = cp.concatenate([a, b], axis=0) # Shape: (4, 2)
392
horizontal = cp.concatenate([a, b], axis=1) # Shape: (2, 4)
393
394
# Stack along new axis
395
stacked = cp.stack([a, b], axis=2) # Shape: (2, 2, 2)
396
```