0
# Array Operations
1
2
Core functionality for creating, reshaping, and manipulating N-dimensional arrays on GPU memory. These operations provide the foundation for all GPU-accelerated computations in CuPy with full NumPy compatibility.
3
4
## Capabilities
5
6
### Array Creation - Basic
7
8
Creates new arrays with specified shapes and initial values, allocating memory on the GPU.
9
10
```python { .api }
11
def empty(shape, dtype=float, order='C'):
12
"""
13
Create an uninitialized array of given shape and type on GPU.
14
15
Parameters:
16
- shape: int or tuple of ints, shape of the array
17
- dtype: data type, optional
18
- order: memory layout ('C' for C-contiguous, 'F' for Fortran-contiguous)
19
20
Returns:
21
cupy.ndarray
22
"""
23
24
def zeros(shape, dtype=float, order='C'):
25
"""
26
Create array filled with zeros.
27
28
Parameters:
29
- shape: int or tuple of ints
30
- dtype: data type, optional
31
- order: memory layout, optional
32
33
Returns:
34
cupy.ndarray
35
"""
36
37
def ones(shape, dtype=float, order='C'):
38
"""
39
Create array filled with ones.
40
41
Parameters:
42
- shape: int or tuple of ints
43
- dtype: data type, optional
44
- order: memory layout, optional
45
46
Returns:
47
cupy.ndarray
48
"""
49
50
def full(shape, fill_value, dtype=None, order='C'):
51
"""
52
Create array filled with specified value.
53
54
Parameters:
55
- shape: int or tuple of ints
56
- fill_value: scalar, value to fill the array
57
- dtype: data type, optional
58
- order: memory layout, optional
59
60
Returns:
61
cupy.ndarray
62
"""
63
64
def identity(n, dtype=None):
65
"""
66
Create identity matrix.
67
68
Parameters:
69
- n: int, number of rows/columns
70
- dtype: data type, optional
71
72
Returns:
73
cupy.ndarray
74
"""
75
76
def eye(N, M=None, k=0, dtype=float, order='C'):
77
"""
78
Create 2-D array with ones on diagonal and zeros elsewhere.
79
80
Parameters:
81
- N: int, number of rows
82
- M: int, number of columns (defaults to N)
83
- k: int, diagonal offset
84
- dtype: data type, optional
85
- order: memory layout, optional
86
87
Returns:
88
cupy.ndarray
89
"""
90
```
91
92
### Array Creation - From Data
93
94
Creates arrays from existing data sources, enabling conversion from various input formats.
95
96
```python { .api }
97
def array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0):
98
"""
99
Create array from array-like object.
100
101
Parameters:
102
- object: array-like, input data
103
- dtype: data type, optional
104
- copy: bool, whether to copy data
105
- order: memory layout
106
- subok: bool, allow subclasses
107
- ndmin: int, minimum dimensions
108
109
Returns:
110
cupy.ndarray
111
"""
112
113
def asarray(a, dtype=None, order=None):
114
"""
115
Convert input to array, no copy if already ndarray.
116
117
Parameters:
118
- a: array-like
119
- dtype: data type, optional
120
- order: memory layout, optional
121
122
Returns:
123
cupy.ndarray
124
"""
125
126
def copy(a, order='K', subok=False):
127
"""
128
Create copy of array.
129
130
Parameters:
131
- a: array-like
132
- order: memory layout
133
- subok: bool, allow subclasses
134
135
Returns:
136
cupy.ndarray
137
"""
138
139
def frombuffer(buffer, dtype=float, count=-1, offset=0):
140
"""
141
Create array from buffer object.
142
143
Parameters:
144
- buffer: buffer object
145
- dtype: data type
146
- count: int, number of items
147
- offset: int, byte offset
148
149
Returns:
150
cupy.ndarray
151
"""
152
153
def fromfunction(function, shape, **kwargs):
154
"""
155
Create array by executing function over each coordinate.
156
157
Parameters:
158
- function: callable, function to call
159
- shape: tuple of ints
160
- kwargs: additional arguments
161
162
Returns:
163
cupy.ndarray
164
"""
165
```
166
167
### Array Creation - Ranges
168
169
Creates arrays with regularly spaced values for numerical computations.
170
171
```python { .api }
172
def arange(start, stop=None, step=1, dtype=None):
173
"""
174
Create array with evenly spaced values within given interval.
175
176
Parameters:
177
- start: number, start of interval
178
- stop: number, end of interval
179
- step: number, spacing between values
180
- dtype: data type, optional
181
182
Returns:
183
cupy.ndarray
184
"""
185
186
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0):
187
"""
188
Create array with evenly spaced numbers over specified interval.
189
190
Parameters:
191
- start: scalar, starting value
192
- stop: scalar, ending value
193
- num: int, number of samples
194
- endpoint: bool, include endpoint
195
- retstep: bool, return step size
196
- dtype: data type, optional
197
- axis: int, axis along which to store samples
198
199
Returns:
200
cupy.ndarray or (cupy.ndarray, float)
201
"""
202
203
def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):
204
"""
205
Create array with numbers spaced evenly on log scale.
206
207
Parameters:
208
- start: scalar, base**start is starting value
209
- stop: scalar, base**stop is ending value
210
- num: int, number of samples
211
- endpoint: bool, include endpoint
212
- base: scalar, base of log space
213
- dtype: data type, optional
214
- axis: int, axis along which to store samples
215
216
Returns:
217
cupy.ndarray
218
"""
219
220
def meshgrid(*xi, copy=True, sparse=False, indexing='xy'):
221
"""
222
Create coordinate matrices from coordinate vectors.
223
224
Parameters:
225
- xi: array-like, 1-D arrays representing coordinates
226
- copy: bool, copy arrays
227
- sparse: bool, return sparse grid
228
- indexing: str, Cartesian ('xy') or matrix ('ij') indexing
229
230
Returns:
231
list of cupy.ndarray
232
"""
233
```
234
235
### Shape Manipulation
236
237
Operations for changing array shapes and dimensions without modifying data.
238
239
```python { .api }
240
def reshape(a, newshape, order='C'):
241
"""
242
Give new shape to array without changing data.
243
244
Parameters:
245
- a: array-like
246
- newshape: int or tuple of ints
247
- order: memory layout
248
249
Returns:
250
cupy.ndarray
251
"""
252
253
def ravel(a, order='C'):
254
"""
255
Return flattened array.
256
257
Parameters:
258
- a: array-like
259
- order: memory layout
260
261
Returns:
262
cupy.ndarray
263
"""
264
265
def transpose(a, axes=None):
266
"""
267
Permute dimensions of array.
268
269
Parameters:
270
- a: array-like
271
- axes: tuple of ints, permutation of dimensions
272
273
Returns:
274
cupy.ndarray
275
"""
276
277
def swapaxes(a, axis1, axis2):
278
"""
279
Interchange two axes of array.
280
281
Parameters:
282
- a: array-like
283
- axis1: int, first axis
284
- axis2: int, second axis
285
286
Returns:
287
cupy.ndarray
288
"""
289
290
def expand_dims(a, axis):
291
"""
292
Expand shape of array by inserting new axes.
293
294
Parameters:
295
- a: array-like
296
- axis: int or tuple of ints, position of new axes
297
298
Returns:
299
cupy.ndarray
300
"""
301
302
def squeeze(a, axis=None):
303
"""
304
Remove single-dimensional entries from shape.
305
306
Parameters:
307
- a: array-like
308
- axis: int or tuple of ints, axes to squeeze
309
310
Returns:
311
cupy.ndarray
312
"""
313
```
314
315
### Array Joining
316
317
Operations for combining multiple arrays into single arrays.
318
319
```python { .api }
320
def concatenate(arrays, axis=0, out=None, dtype=None, casting="same_kind"):
321
"""
322
Join sequence of arrays along existing axis.
323
324
Parameters:
325
- arrays: sequence of array-like
326
- axis: int, axis to concatenate along
327
- out: ndarray, destination array
328
- dtype: data type
329
- casting: casting mode
330
331
Returns:
332
cupy.ndarray
333
"""
334
335
def stack(arrays, axis=0, out=None):
336
"""
337
Join sequence of arrays along new axis.
338
339
Parameters:
340
- arrays: sequence of array-like
341
- axis: int, axis to stack along
342
- out: ndarray, destination array
343
344
Returns:
345
cupy.ndarray
346
"""
347
348
def vstack(tup):
349
"""
350
Stack arrays vertically (row-wise).
351
352
Parameters:
353
- tup: sequence of arrays
354
355
Returns:
356
cupy.ndarray
357
"""
358
359
def hstack(tup):
360
"""
361
Stack arrays horizontally (column-wise).
362
363
Parameters:
364
- tup: sequence of arrays
365
366
Returns:
367
cupy.ndarray
368
"""
369
370
def dstack(tup):
371
"""
372
Stack arrays depth-wise (along third axis).
373
374
Parameters:
375
- tup: sequence of arrays
376
377
Returns:
378
cupy.ndarray
379
"""
380
```
381
382
### Array Splitting
383
384
Operations for dividing arrays into multiple sub-arrays.
385
386
```python { .api }
387
def split(ary, indices_or_sections, axis=0):
388
"""
389
Split array into sub-arrays.
390
391
Parameters:
392
- ary: ndarray, array to split
393
- indices_or_sections: int or array of ints, split points
394
- axis: int, axis to split along
395
396
Returns:
397
list of cupy.ndarray
398
"""
399
400
def hsplit(ary, indices_or_sections):
401
"""
402
Split array horizontally.
403
404
Parameters:
405
- ary: ndarray
406
- indices_or_sections: int or array of ints
407
408
Returns:
409
list of cupy.ndarray
410
"""
411
412
def vsplit(ary, indices_or_sections):
413
"""
414
Split array vertically.
415
416
Parameters:
417
- ary: ndarray
418
- indices_or_sections: int or array of ints
419
420
Returns:
421
list of cupy.ndarray
422
"""
423
424
def array_split(ary, indices_or_sections, axis=0):
425
"""
426
Split array into sub-arrays allowing unequal sizes.
427
428
Parameters:
429
- ary: ndarray
430
- indices_or_sections: int or array of ints
431
- axis: int, axis to split along
432
433
Returns:
434
list of cupy.ndarray
435
"""
436
```
437
438
### Tiling and Repetition
439
440
Operations for repeating and tiling arrays to create larger arrays.
441
442
```python { .api }
443
def tile(A, reps):
444
"""
445
Construct array by repeating array given number of times.
446
447
Parameters:
448
- A: array-like
449
- reps: int or tuple of ints, repetitions along each axis
450
451
Returns:
452
cupy.ndarray
453
"""
454
455
def repeat(a, repeats, axis=None):
456
"""
457
Repeat elements of array.
458
459
Parameters:
460
- a: array-like
461
- repeats: int or array of ints, number of repetitions
462
- axis: int, axis along which to repeat
463
464
Returns:
465
cupy.ndarray
466
"""
467
```
468
469
### Memory Layout Operations
470
471
Operations for controlling memory layout and contiguity of arrays.
472
473
```python { .api }
474
def ascontiguousarray(a, dtype=None):
475
"""
476
Return contiguous array in C order.
477
478
Parameters:
479
- a: array-like
480
- dtype: data type, optional
481
482
Returns:
483
cupy.ndarray
484
"""
485
486
def asfortranarray(a, dtype=None):
487
"""
488
Return contiguous array in Fortran order.
489
490
Parameters:
491
- a: array-like
492
- dtype: data type, optional
493
494
Returns:
495
cupy.ndarray
496
"""
497
498
def require(a, dtype=None, requirements=None):
499
"""
500
Return array satisfying requirements.
501
502
Parameters:
503
- a: array-like
504
- dtype: data type, optional
505
- requirements: str or list of str, array requirements
506
507
Returns:
508
cupy.ndarray
509
"""
510
```
511
512
## Usage Examples
513
514
### Basic Array Creation
515
516
```python
517
import cupy as cp
518
519
# Create basic arrays
520
zeros_array = cp.zeros((3, 4))
521
ones_matrix = cp.ones((2, 2), dtype=cp.float32)
522
identity_mat = cp.identity(3)
523
524
# Create from data
525
data = [[1, 2, 3], [4, 5, 6]]
526
gpu_array = cp.array(data)
527
528
# Create ranges
529
sequence = cp.arange(10)
530
linear_space = cp.linspace(0, 1, 100)
531
```
532
533
### Shape Manipulation
534
535
```python
536
import cupy as cp
537
538
# Create and reshape
539
original = cp.arange(12)
540
reshaped = cp.reshape(original, (3, 4))
541
transposed = cp.transpose(reshaped)
542
543
# Add/remove dimensions
544
expanded = cp.expand_dims(original, axis=0)
545
squeezed = cp.squeeze(expanded)
546
```
547
548
### Array Combination
549
550
```python
551
import cupy as cp
552
553
# Stack arrays
554
a = cp.array([1, 2, 3])
555
b = cp.array([4, 5, 6])
556
557
horizontal = cp.hstack([a, b])
558
vertical = cp.vstack([a, b])
559
stacked = cp.stack([a, b], axis=0)
560
561
# Concatenate along axis
562
c = cp.array([[1, 2], [3, 4]])
563
d = cp.array([[5, 6], [7, 8]])
564
combined = cp.concatenate([c, d], axis=1)
565
```