or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array-creation.mdarray-manipulation.mdbinary-operations.mdcuda.mdfft.mdindex.mdindexing-searching.mdlinalg.mdlogic-functions.mdmath-functions.mdmemory-performance.mdrandom.mdsorting-counting.mdstatistics.md

array-creation.mddocs/

0

# Array Creation and Manipulation

1

2

Core array creation functions that mirror NumPy's array creation API while creating arrays on GPU memory. These functions form the foundation of CuPy's array operations and provide seamless migration from NumPy code.

3

4

## Capabilities

5

6

### Basic Array Creation

7

8

Create arrays with specified shapes, data types, and initial values. These functions allocate GPU memory and initialize arrays with the requested data.

9

10

```python { .api }

11

def array(obj, dtype=None, copy=True, order='K', subok=False, ndmin=0):

12

"""

13

Create an array from data on GPU.

14

15

Parameters:

16

- obj: array-like, input data

17

- dtype: data type, optional

18

- copy: bool, whether to copy data

19

- order: memory layout ('C', 'F', 'A', 'K')

20

- subok: bool, allow subclasses

21

- ndmin: int, minimum dimensions

22

23

Returns:

24

cupy.ndarray: Array on GPU

25

"""

26

27

def asarray(a, dtype=None, order=None):

28

"""

29

Convert input to array.

30

31

Parameters:

32

- a: array-like, input data

33

- dtype: data type, optional

34

- order: memory layout, optional

35

36

Returns:

37

cupy.ndarray: Array on GPU

38

"""

39

40

def ascontiguousarray(a, dtype=None):

41

"""

42

Return C-contiguous array.

43

44

Parameters:

45

- a: array-like, input data

46

- dtype: data type, optional

47

48

Returns:

49

cupy.ndarray: C-contiguous array on GPU

50

"""

51

52

def copy(a, order='K'):

53

"""

54

Return copy of array.

55

56

Parameters:

57

- a: array-like, input data

58

- order: memory layout ('C', 'F', 'A', 'K')

59

60

Returns:

61

cupy.ndarray: Copy of array on GPU

62

"""

63

```

64

65

### Constant Arrays

66

67

Create arrays filled with constant values including zeros, ones, and custom fill values.

68

69

```python { .api }

70

def zeros(shape, dtype=float, order='C'):

71

"""

72

Create array filled with zeros.

73

74

Parameters:

75

- shape: int or tuple, array shape

76

- dtype: data type, default float

77

- order: memory layout ('C', 'F')

78

79

Returns:

80

cupy.ndarray: Zero-filled array on GPU

81

"""

82

83

def zeros_like(a, dtype=None, order='K', subok=True, shape=None):

84

"""

85

Create zeros array with same shape and type.

86

87

Parameters:

88

- a: array-like, reference array

89

- dtype: data type, optional override

90

- order: memory layout, optional

91

- subok: bool, allow subclasses

92

- shape: tuple, optional shape override

93

94

Returns:

95

cupy.ndarray: Zero-filled array on GPU

96

"""

97

98

def ones(shape, dtype=None, order='C'):

99

"""

100

Create array filled with ones.

101

102

Parameters:

103

- shape: int or tuple, array shape

104

- dtype: data type, default float

105

- order: memory layout ('C', 'F')

106

107

Returns:

108

cupy.ndarray: One-filled array on GPU

109

"""

110

111

def ones_like(a, dtype=None, order='K', subok=True, shape=None):

112

"""

113

Create ones array with same shape and type.

114

115

Parameters:

116

- a: array-like, reference array

117

- dtype: data type, optional override

118

- order: memory layout, optional

119

- subok: bool, allow subclasses

120

- shape: tuple, optional shape override

121

122

Returns:

123

cupy.ndarray: One-filled array on GPU

124

"""

125

126

def full(shape, fill_value, dtype=None, order='C'):

127

"""

128

Create array filled with specified value.

129

130

Parameters:

131

- shape: int or tuple, array shape

132

- fill_value: scalar, fill value

133

- dtype: data type, optional

134

- order: memory layout ('C', 'F')

135

136

Returns:

137

cupy.ndarray: Filled array on GPU

138

"""

139

140

def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None):

141

"""

142

Create filled array with same shape and type.

143

144

Parameters:

145

- a: array-like, reference array

146

- fill_value: scalar, fill value

147

- dtype: data type, optional override

148

- order: memory layout, optional

149

- subok: bool, allow subclasses

150

- shape: tuple, optional shape override

151

152

Returns:

153

cupy.ndarray: Filled array on GPU

154

"""

155

156

def empty(shape, dtype=float, order='C'):

157

"""

158

Create uninitialized array.

159

160

Parameters:

161

- shape: int or tuple, array shape

162

- dtype: data type, default float

163

- order: memory layout ('C', 'F')

164

165

Returns:

166

cupy.ndarray: Uninitialized array on GPU

167

"""

168

169

def empty_like(a, dtype=None, order='K', subok=True, shape=None):

170

"""

171

Create uninitialized array with same shape and type.

172

173

Parameters:

174

- a: array-like, reference array

175

- dtype: data type, optional override

176

- order: memory layout, optional

177

- subok: bool, allow subclasses

178

- shape: tuple, optional shape override

179

180

Returns:

181

cupy.ndarray: Uninitialized array on GPU

182

"""

183

```

184

185

### Array Ranges and Sequences

186

187

Create arrays with evenly spaced values, linear sequences, and logarithmic sequences.

188

189

```python { .api }

190

def arange(start, stop=None, step=None, dtype=None):

191

"""

192

Create array with evenly spaced values.

193

194

Parameters:

195

- start: scalar, start value (or stop if single argument)

196

- stop: scalar, stop value, optional

197

- step: scalar, step size, optional

198

- dtype: data type, optional

199

200

Returns:

201

cupy.ndarray: Array with evenly spaced values on GPU

202

"""

203

204

def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0):

205

"""

206

Create array with linearly spaced values.

207

208

Parameters:

209

- start: scalar, start value

210

- stop: scalar, stop value

211

- num: int, number of samples

212

- endpoint: bool, include endpoint

213

- retstep: bool, return step size

214

- dtype: data type, optional

215

- axis: int, axis for multi-dimensional start/stop

216

217

Returns:

218

cupy.ndarray or tuple: Linearly spaced array on GPU, optionally with step size

219

"""

220

221

def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):

222

"""

223

Create array with logarithmically spaced values.

224

225

Parameters:

226

- start: scalar, start exponent

227

- stop: scalar, stop exponent

228

- num: int, number of samples

229

- endpoint: bool, include endpoint

230

- base: scalar, logarithm base

231

- dtype: data type, optional

232

- axis: int, axis for multi-dimensional start/stop

233

234

Returns:

235

cupy.ndarray: Logarithmically spaced array on GPU

236

"""

237

238

def meshgrid(*xi, indexing='xy', sparse=False, copy=True):

239

"""

240

Create coordinate matrices from coordinate vectors.

241

242

Parameters:

243

- xi: array-like, coordinate vectors

244

- indexing: str, indexing mode ('xy' or 'ij')

245

- sparse: bool, return sparse grid

246

- copy: bool, copy input arrays

247

248

Returns:

249

list of cupy.ndarray: Coordinate matrices on GPU

250

"""

251

```

252

253

### Matrix Creation

254

255

Create special matrices including identity matrices, diagonal matrices, and triangular matrices.

256

257

```python { .api }

258

def eye(N, M=None, k=0, dtype=float, order='C'):

259

"""

260

Create 2D identity array.

261

262

Parameters:

263

- N: int, number of rows

264

- M: int, number of columns, optional

265

- k: int, diagonal offset

266

- dtype: data type, default float

267

- order: memory layout ('C', 'F')

268

269

Returns:

270

cupy.ndarray: Identity array on GPU

271

"""

272

273

def identity(n, dtype=None):

274

"""

275

Create identity matrix.

276

277

Parameters:

278

- n: int, size of matrix

279

- dtype: data type, optional

280

281

Returns:

282

cupy.ndarray: Identity matrix on GPU

283

"""

284

285

def diag(v, k=0):

286

"""

287

Extract diagonal or create diagonal matrix.

288

289

Parameters:

290

- v: array-like, diagonal values or input array

291

- k: int, diagonal offset

292

293

Returns:

294

cupy.ndarray: Diagonal array on GPU

295

"""

296

297

def diagflat(v, k=0):

298

"""

299

Create 2D array with flattened input as diagonal.

300

301

Parameters:

302

- v: array-like, diagonal values

303

- k: int, diagonal offset

304

305

Returns:

306

cupy.ndarray: 2D diagonal array on GPU

307

"""

308

309

def tri(N, M=None, k=0, dtype=float):

310

"""

311

Create array with ones at and below diagonal.

312

313

Parameters:

314

- N: int, number of rows

315

- M: int, number of columns, optional

316

- k: int, diagonal offset

317

- dtype: data type, default float

318

319

Returns:

320

cupy.ndarray: Lower triangular array on GPU

321

"""

322

323

def tril(m, k=0):

324

"""

325

Lower triangle of array.

326

327

Parameters:

328

- m: array-like, input array

329

- k: int, diagonal offset

330

331

Returns:

332

cupy.ndarray: Lower triangular array on GPU

333

"""

334

335

def triu(m, k=0):

336

"""

337

Upper triangle of array.

338

339

Parameters:

340

- m: array-like, input array

341

- k: int, diagonal offset

342

343

Returns:

344

cupy.ndarray: Upper triangular array on GPU

345

"""

346

```

347

348

### Array Manipulation

349

350

Functions for reshaping, transposing, and rearranging arrays while maintaining data in GPU memory.

351

352

```python { .api }

353

def reshape(a, newshape, order='C'):

354

"""

355

Change array shape.

356

357

Parameters:

358

- a: array-like, input array

359

- newshape: int or tuple, new shape

360

- order: memory layout ('C', 'F', 'A')

361

362

Returns:

363

cupy.ndarray: Reshaped array on GPU

364

"""

365

366

def ravel(a, order='C'):

367

"""

368

Return flattened array.

369

370

Parameters:

371

- a: array-like, input array

372

- order: memory layout ('C', 'F', 'A', 'K')

373

374

Returns:

375

cupy.ndarray: Flattened array on GPU

376

"""

377

378

def transpose(a, axes=None):

379

"""

380

Reverse or permute axes.

381

382

Parameters:

383

- a: array-like, input array

384

- axes: tuple, permutation of axes, optional

385

386

Returns:

387

cupy.ndarray: Transposed array on GPU

388

"""

389

390

def squeeze(a, axis=None):

391

"""

392

Remove single-dimensional entries.

393

394

Parameters:

395

- a: array-like, input array

396

- axis: int or tuple, axes to squeeze, optional

397

398

Returns:

399

cupy.ndarray: Squeezed array on GPU

400

"""

401

402

def expand_dims(a, axis):

403

"""

404

Expand array dimensions.

405

406

Parameters:

407

- a: array-like, input array

408

- axis: int or tuple, position of new axes

409

410

Returns:

411

cupy.ndarray: Array with expanded dimensions on GPU

412

"""

413

```

414

415

### Array Joining and Splitting

416

417

Functions for combining multiple arrays and splitting arrays into sub-arrays.

418

419

```python { .api }

420

def concatenate(arrays, axis=0, out=None, dtype=None):

421

"""

422

Join arrays along existing axis.

423

424

Parameters:

425

- arrays: sequence of arrays, input arrays

426

- axis: int, concatenation axis

427

- out: array, output array, optional

428

- dtype: data type, optional

429

430

Returns:

431

cupy.ndarray: Concatenated array on GPU

432

"""

433

434

def stack(arrays, axis=0, out=None):

435

"""

436

Join arrays along new axis.

437

438

Parameters:

439

- arrays: sequence of arrays, input arrays

440

- axis: int, stacking axis

441

- out: array, output array, optional

442

443

Returns:

444

cupy.ndarray: Stacked array on GPU

445

"""

446

447

def vstack(tup):

448

"""

449

Stack arrays vertically.

450

451

Parameters:

452

- tup: sequence of arrays, input arrays

453

454

Returns:

455

cupy.ndarray: Vertically stacked array on GPU

456

"""

457

458

def hstack(tup):

459

"""

460

Stack arrays horizontally.

461

462

Parameters:

463

- tup: sequence of arrays, input arrays

464

465

Returns:

466

cupy.ndarray: Horizontally stacked array on GPU

467

"""

468

469

def split(ary, indices_or_sections, axis=0):

470

"""

471

Split array into sub-arrays.

472

473

Parameters:

474

- ary: array-like, input array

475

- indices_or_sections: int or array, split points

476

- axis: int, splitting axis

477

478

Returns:

479

list of cupy.ndarray: Sub-arrays on GPU

480

"""

481

```

482

483

## Usage Examples

484

485

### Creating and Converting Arrays

486

487

```python

488

import cupy as cp

489

import numpy as np

490

491

# Create arrays on GPU

492

gpu_zeros = cp.zeros((3, 4), dtype=cp.float32)

493

gpu_ones = cp.ones_like(gpu_zeros)

494

gpu_range = cp.arange(12).reshape(3, 4)

495

496

# Convert between CPU and GPU

497

cpu_array = np.array([[1, 2], [3, 4]])

498

gpu_array = cp.asarray(cpu_array) # CPU to GPU

499

back_to_cpu = cp.asnumpy(gpu_array) # GPU to CPU

500

501

# Create sequences

502

linear = cp.linspace(0, 10, 100)

503

log_scale = cp.logspace(0, 3, 50) # 10^0 to 10^3

504

```

505

506

### Matrix Operations

507

508

```python

509

# Create special matrices

510

identity = cp.eye(5)

511

diagonal = cp.diag([1, 2, 3, 4, 5])

512

upper_tri = cp.triu(cp.ones((4, 4)))

513

514

# Coordinate grids for plotting

515

x = cp.linspace(-5, 5, 100)

516

y = cp.linspace(-3, 3, 60)

517

X, Y = cp.meshgrid(x, y)

518

Z = cp.sin(cp.sqrt(X**2 + Y**2))

519

```