0
# Array Creation and Manipulation
1
2
Core array creation functions and manipulation operations that provide the foundation for GPU-accelerated computing with CuPy. These functions create and modify GPU arrays while maintaining full NumPy API compatibility.
3
4
## Capabilities
5
6
### Basic Array Creation
7
8
Creates arrays with specified shapes and values, providing the fundamental building blocks for GPU computations.
9
10
```python { .api }
11
def array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0):
12
"""
13
Create an array on GPU from an array-like object.
14
15
Parameters:
16
- object: array-like, input data to convert to GPU array
17
- dtype: data type, if None, inferred from input
18
- copy: bool, whether to copy data (default True)
19
- order: {'C', 'F', 'A', 'K'}, memory layout
20
- subok: bool, whether to allow subclasses
21
- ndmin: int, minimum number of dimensions
22
23
Returns:
24
cupy.ndarray: GPU array
25
"""
26
27
def asarray(a, dtype=None, order=None):
28
"""
29
Convert input to GPU array.
30
31
Parameters:
32
- a: array-like, input data
33
- dtype: data type, if None, preserve input dtype
34
- order: {'C', 'F', 'A', 'K'}, memory layout
35
36
Returns:
37
cupy.ndarray: GPU array
38
"""
39
40
def copy(a, order='K'):
41
"""
42
Return a copy of the array.
43
44
Parameters:
45
- a: cupy.ndarray, input array
46
- order: {'C', 'F', 'A', 'K'}, memory layout of copy
47
48
Returns:
49
cupy.ndarray: Copy of input array
50
"""
51
```
52
53
### Array Initialization
54
55
Create arrays with specific initialization patterns including zeros, ones, and uninitialized arrays.
56
57
```python { .api }
58
def zeros(shape, dtype=float, order='C'):
59
"""
60
Create array filled with zeros.
61
62
Parameters:
63
- shape: int or tuple of ints, shape of array
64
- dtype: data type, default float
65
- order: {'C', 'F'}, memory layout
66
67
Returns:
68
cupy.ndarray: Array of zeros
69
"""
70
71
def ones(shape, dtype=None, order='C'):
72
"""
73
Create array filled with ones.
74
75
Parameters:
76
- shape: int or tuple of ints, shape of array
77
- dtype: data type, default None (float)
78
- order: {'C', 'F'}, memory layout
79
80
Returns:
81
cupy.ndarray: Array of ones
82
"""
83
84
def empty(shape, dtype=float, order='C'):
85
"""
86
Create uninitialized array.
87
88
Parameters:
89
- shape: int or tuple of ints, shape of array
90
- dtype: data type, default float
91
- order: {'C', 'F'}, memory layout
92
93
Returns:
94
cupy.ndarray: Uninitialized array
95
"""
96
97
def full(shape, fill_value, dtype=None, order='C'):
98
"""
99
Create array filled with specified value.
100
101
Parameters:
102
- shape: int or tuple of ints, shape of array
103
- fill_value: scalar, fill value
104
- dtype: data type, if None, inferred from fill_value
105
- order: {'C', 'F'}, memory layout
106
107
Returns:
108
cupy.ndarray: Array filled with fill_value
109
"""
110
```
111
112
### Array-like Creation
113
114
Create arrays with same shape and properties as existing arrays.
115
116
```python { .api }
117
def zeros_like(a, dtype=None, order='K', subok=True, shape=None):
118
"""
119
Create zeros array with same shape as input.
120
121
Parameters:
122
- a: array-like, reference array for shape
123
- dtype: data type, if None, use dtype of a
124
- order: {'C', 'F', 'A', 'K'}, memory layout
125
- subok: bool, whether to allow subclasses
126
- shape: tuple, override shape if provided
127
128
Returns:
129
cupy.ndarray: Array of zeros with shape of a
130
"""
131
132
def ones_like(a, dtype=None, order='K', subok=True, shape=None):
133
"""Create ones array with same shape as input."""
134
135
def empty_like(a, dtype=None, order='K', subok=True, shape=None):
136
"""Create uninitialized array with same shape as input."""
137
138
def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None):
139
"""Create filled array with same shape as input."""
140
```
141
142
### Range and Sequence Creation
143
144
Generate arrays with arithmetic and geometric sequences.
145
146
```python { .api }
147
def arange(start, stop=None, step=1, dtype=None):
148
"""
149
Create array with evenly spaced values within given interval.
150
151
Parameters:
152
- start: number, start of interval (or stop if stop is None)
153
- stop: number, end of interval (exclusive)
154
- step: number, spacing between values
155
- dtype: data type, if None, inferred from inputs
156
157
Returns:
158
cupy.ndarray: Array of evenly spaced values
159
"""
160
161
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0):
162
"""
163
Create array with linearly spaced values.
164
165
Parameters:
166
- start: scalar, start value
167
- stop: scalar, end value
168
- num: int, number of samples (default 50)
169
- endpoint: bool, whether to include stop value
170
- retstep: bool, whether to return step size
171
- dtype: data type, if None, inferred from inputs
172
- axis: int, axis along which to create samples
173
174
Returns:
175
cupy.ndarray: Array of linearly spaced values
176
tuple: (samples, step) if retstep=True
177
"""
178
179
def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):
180
"""
181
Create array with logarithmically spaced values.
182
183
Parameters:
184
- start: scalar, base**start is starting value
185
- stop: scalar, base**stop is final value
186
- num: int, number of samples
187
- endpoint: bool, whether to include stop value
188
- base: float, base of log space
189
- dtype: data type, if None, inferred
190
- axis: int, axis along which to create samples
191
192
Returns:
193
cupy.ndarray: Array of log-spaced values
194
"""
195
```
196
197
### Matrix Creation
198
199
Create special matrix structures including identity matrices and diagonal arrays.
200
201
```python { .api }
202
def eye(N, M=None, k=0, dtype=float, order='C'):
203
"""
204
Create identity matrix.
205
206
Parameters:
207
- N: int, number of rows
208
- M: int, number of columns (default N)
209
- k: int, diagonal offset
210
- dtype: data type
211
- order: {'C', 'F'}, memory layout
212
213
Returns:
214
cupy.ndarray: Identity matrix
215
"""
216
217
def identity(n, dtype=None):
218
"""
219
Create identity matrix of size n x n.
220
221
Parameters:
222
- n: int, size of matrix
223
- dtype: data type, default None (float)
224
225
Returns:
226
cupy.ndarray: n x n identity matrix
227
"""
228
229
def diag(v, k=0):
230
"""
231
Extract diagonal or create diagonal matrix.
232
233
Parameters:
234
- v: array-like, diagonal elements or matrix
235
- k: int, diagonal offset
236
237
Returns:
238
cupy.ndarray: Diagonal elements or diagonal matrix
239
"""
240
241
def diagflat(v, k=0):
242
"""
243
Create 2D array with flattened input as diagonal.
244
245
Parameters:
246
- v: array-like, input to flatten and use as diagonal
247
- k: int, diagonal offset
248
249
Returns:
250
cupy.ndarray: 2D array with v as diagonal
251
"""
252
```
253
254
### Shape Manipulation
255
256
Modify array shapes and dimensions without changing data.
257
258
```python { .api }
259
def reshape(a, newshape, order='C'):
260
"""
261
Return array with new shape.
262
263
Parameters:
264
- a: cupy.ndarray, input array
265
- newshape: int or tuple of ints, new shape
266
- order: {'C', 'F', 'A'}, memory layout
267
268
Returns:
269
cupy.ndarray: Array with new shape
270
"""
271
272
def ravel(a, order='C'):
273
"""
274
Return flattened array.
275
276
Parameters:
277
- a: array-like, input array
278
- order: {'C', 'F', 'A', 'K'}, flattening order
279
280
Returns:
281
cupy.ndarray: 1D array
282
"""
283
284
def flatten(a, order='C'):
285
"""Return copy of array collapsed into 1D."""
286
287
def squeeze(a, axis=None):
288
"""
289
Remove single-dimensional entries from shape.
290
291
Parameters:
292
- a: cupy.ndarray, input array
293
- axis: None or int or tuple of ints, axes to squeeze
294
295
Returns:
296
cupy.ndarray: Array with squeezed dimensions
297
"""
298
299
def expand_dims(a, axis):
300
"""
301
Expand array dimensions.
302
303
Parameters:
304
- a: array-like, input array
305
- axis: int or tuple of ints, position of new axes
306
307
Returns:
308
cupy.ndarray: Array with expanded dimensions
309
"""
310
```
311
312
### Array Joining
313
314
Combine multiple arrays along various axes.
315
316
```python { .api }
317
def concatenate(arrays, axis=0, out=None, dtype=None, casting="same_kind"):
318
"""
319
Join arrays along existing axis.
320
321
Parameters:
322
- arrays: sequence of arrays, arrays to concatenate
323
- axis: int, axis along which to concatenate
324
- out: cupy.ndarray, output array
325
- dtype: data type, output data type
326
- casting: casting rule for data type conversion
327
328
Returns:
329
cupy.ndarray: Concatenated array
330
"""
331
332
def stack(arrays, axis=0, out=None):
333
"""
334
Join arrays along new axis.
335
336
Parameters:
337
- arrays: sequence of arrays, arrays to stack
338
- axis: int, axis along which to stack
339
- out: cupy.ndarray, output array
340
341
Returns:
342
cupy.ndarray: Stacked array
343
"""
344
345
def vstack(arrays):
346
"""Stack arrays vertically (row-wise)."""
347
348
def hstack(arrays):
349
"""Stack arrays horizontally (column-wise)."""
350
351
def dstack(arrays):
352
"""Stack arrays depth-wise (along third axis)."""
353
```
354
355
### Array Splitting
356
357
Split arrays into sub-arrays.
358
359
```python { .api }
360
def split(ary, indices_or_sections, axis=0):
361
"""
362
Split array into sub-arrays.
363
364
Parameters:
365
- ary: cupy.ndarray, array to split
366
- indices_or_sections: int or 1D array, split points
367
- axis: int, axis along which to split
368
369
Returns:
370
list: List of sub-arrays
371
"""
372
373
def array_split(ary, indices_or_sections, axis=0):
374
"""Split array into sub-arrays of equal or near-equal size."""
375
376
def hsplit(ary, indices_or_sections):
377
"""Split array horizontally."""
378
379
def vsplit(ary, indices_or_sections):
380
"""Split array vertically."""
381
382
def dsplit(ary, indices_or_sections):
383
"""Split array depth-wise."""
384
```
385
386
### Data Type Conversion
387
388
Convert arrays between different data types and memory layouts.
389
390
```python { .api }
391
def astype(a, dtype, order='K', casting='unsafe', subok=True, copy=True):
392
"""
393
Cast array to specified type.
394
395
Parameters:
396
- a: cupy.ndarray, input array
397
- dtype: data type, target data type
398
- order: {'C', 'F', 'A', 'K'}, memory layout
399
- casting: casting rule
400
- subok: bool, allow subclasses
401
- copy: bool, whether to copy if dtype matches
402
403
Returns:
404
cupy.ndarray: Array with new dtype
405
"""
406
407
def ascontiguousarray(a, dtype=None):
408
"""Return C-contiguous array."""
409
410
def asfortranarray(a, dtype=None):
411
"""Return Fortran-contiguous array."""
412
```
413
414
## Usage Examples
415
416
### Creating and Manipulating Arrays
417
418
```python
419
import cupy as cp
420
421
# Create basic arrays
422
a = cp.array([1, 2, 3, 4, 5])
423
b = cp.zeros((3, 4))
424
c = cp.ones((2, 3), dtype=cp.float32)
425
426
# Create sequences
427
x = cp.arange(0, 10, 0.1)
428
y = cp.linspace(0, 1, 100)
429
430
# Shape manipulation
431
reshaped = cp.reshape(a, (5, 1))
432
flattened = cp.ravel(b)
433
434
# Array joining
435
combined = cp.concatenate([a, a], axis=0)
436
stacked = cp.stack([a, a], axis=1)
437
438
# Data type conversion
439
float_array = a.astype(cp.float64)
440
```