Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.10/site-packages/numpy/matrixlib/defmatrix.py: 25%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

238 statements  

1__all__ = ['matrix', 'bmat', 'asmatrix'] 

2 

3import sys 

4import warnings 

5import ast 

6 

7from .._utils import set_module 

8import numpy._core.numeric as N 

9from numpy._core.numeric import concatenate, isscalar 

10# While not in __all__, matrix_power used to be defined here, so we import 

11# it for backward compatibility. 

12from numpy.linalg import matrix_power 

13 

14 

15def _convert_from_string(data): 

16 for char in '[]': 

17 data = data.replace(char, '') 

18 

19 rows = data.split(';') 

20 newdata = [] 

21 for count, row in enumerate(rows): 

22 trow = row.split(',') 

23 newrow = [] 

24 for col in trow: 

25 temp = col.split() 

26 newrow.extend(map(ast.literal_eval, temp)) 

27 if count == 0: 

28 Ncols = len(newrow) 

29 elif len(newrow) != Ncols: 

30 raise ValueError("Rows not the same size.") 

31 newdata.append(newrow) 

32 return newdata 

33 

34 

35@set_module('numpy') 

36def asmatrix(data, dtype=None): 

37 """ 

38 Interpret the input as a matrix. 

39 

40 Unlike `matrix`, `asmatrix` does not make a copy if the input is already 

41 a matrix or an ndarray. Equivalent to ``matrix(data, copy=False)``. 

42 

43 Parameters 

44 ---------- 

45 data : array_like 

46 Input data. 

47 dtype : data-type 

48 Data-type of the output matrix. 

49 

50 Returns 

51 ------- 

52 mat : matrix 

53 `data` interpreted as a matrix. 

54 

55 Examples 

56 -------- 

57 >>> import numpy as np 

58 >>> x = np.array([[1, 2], [3, 4]]) 

59 

60 >>> m = np.asmatrix(x) 

61 

62 >>> x[0,0] = 5 

63 

64 >>> m 

65 matrix([[5, 2], 

66 [3, 4]]) 

67 

68 """ 

69 return matrix(data, dtype=dtype, copy=False) 

70 

71 

72@set_module('numpy') 

73class matrix(N.ndarray): 

74 """ 

75 matrix(data, dtype=None, copy=True) 

76 

77 Returns a matrix from an array-like object, or from a string of data. 

78 

79 A matrix is a specialized 2-D array that retains its 2-D nature 

80 through operations. It has certain special operators, such as ``*`` 

81 (matrix multiplication) and ``**`` (matrix power). 

82 

83 .. note:: It is no longer recommended to use this class, even for linear 

84 algebra. Instead use regular arrays. The class may be removed 

85 in the future. 

86 

87 Parameters 

88 ---------- 

89 data : array_like or string 

90 If `data` is a string, it is interpreted as a matrix with commas 

91 or spaces separating columns, and semicolons separating rows. 

92 dtype : data-type 

93 Data-type of the output matrix. 

94 copy : bool 

95 If `data` is already an `ndarray`, then this flag determines 

96 whether the data is copied (the default), or whether a view is 

97 constructed. 

98 

99 See Also 

100 -------- 

101 array 

102 

103 Examples 

104 -------- 

105 >>> import numpy as np 

106 >>> a = np.matrix('1 2; 3 4') 

107 >>> a 

108 matrix([[1, 2], 

109 [3, 4]]) 

110 

111 >>> np.matrix([[1, 2], [3, 4]]) 

112 matrix([[1, 2], 

113 [3, 4]]) 

114 

115 """ 

116 __array_priority__ = 10.0 

117 def __new__(subtype, data, dtype=None, copy=True): 

118 warnings.warn('the matrix subclass is not the recommended way to ' 

119 'represent matrices or deal with linear algebra (see ' 

120 'https://docs.scipy.org/doc/numpy/user/' 

121 'numpy-for-matlab-users.html). ' 

122 'Please adjust your code to use regular ndarray.', 

123 PendingDeprecationWarning, stacklevel=2) 

124 if isinstance(data, matrix): 

125 dtype2 = data.dtype 

126 if (dtype is None): 

127 dtype = dtype2 

128 if (dtype2 == dtype) and (not copy): 

129 return data 

130 return data.astype(dtype) 

131 

132 if isinstance(data, N.ndarray): 

133 if dtype is None: 

134 intype = data.dtype 

135 else: 

136 intype = N.dtype(dtype) 

137 new = data.view(subtype) 

138 if intype != data.dtype: 

139 return new.astype(intype) 

140 if copy: 

141 return new.copy() 

142 else: 

143 return new 

144 

145 if isinstance(data, str): 

146 data = _convert_from_string(data) 

147 

148 # now convert data to an array 

149 copy = None if not copy else True 

150 arr = N.array(data, dtype=dtype, copy=copy) 

151 ndim = arr.ndim 

152 shape = arr.shape 

153 if (ndim > 2): 

154 raise ValueError("matrix must be 2-dimensional") 

155 elif ndim == 0: 

156 shape = (1, 1) 

157 elif ndim == 1: 

158 shape = (1, shape[0]) 

159 

160 order = 'C' 

161 if (ndim == 2) and arr.flags.fortran: 

162 order = 'F' 

163 

164 if not (order or arr.flags.contiguous): 

165 arr = arr.copy() 

166 

167 ret = N.ndarray.__new__(subtype, shape, arr.dtype, 

168 buffer=arr, 

169 order=order) 

170 return ret 

171 

172 def __array_finalize__(self, obj): 

173 self._getitem = False 

174 if (isinstance(obj, matrix) and obj._getitem): 

175 return 

176 ndim = self.ndim 

177 if (ndim == 2): 

178 return 

179 if (ndim > 2): 

180 newshape = tuple([x for x in self.shape if x > 1]) 

181 ndim = len(newshape) 

182 if ndim == 2: 

183 self.shape = newshape 

184 return 

185 elif (ndim > 2): 

186 raise ValueError("shape too large to be a matrix.") 

187 else: 

188 newshape = self.shape 

189 if ndim == 0: 

190 self.shape = (1, 1) 

191 elif ndim == 1: 

192 self.shape = (1, newshape[0]) 

193 return 

194 

195 def __getitem__(self, index): 

196 self._getitem = True 

197 

198 try: 

199 out = N.ndarray.__getitem__(self, index) 

200 finally: 

201 self._getitem = False 

202 

203 if not isinstance(out, N.ndarray): 

204 return out 

205 

206 if out.ndim == 0: 

207 return out[()] 

208 if out.ndim == 1: 

209 sh = out.shape[0] 

210 # Determine when we should have a column array 

211 try: 

212 n = len(index) 

213 except Exception: 

214 n = 0 

215 if n > 1 and isscalar(index[1]): 

216 out.shape = (sh, 1) 

217 else: 

218 out.shape = (1, sh) 

219 return out 

220 

221 def __mul__(self, other): 

222 if isinstance(other, (N.ndarray, list, tuple)) : 

223 # This promotes 1-D vectors to row vectors 

224 return N.dot(self, asmatrix(other)) 

225 if isscalar(other) or not hasattr(other, '__rmul__') : 

226 return N.dot(self, other) 

227 return NotImplemented 

228 

229 def __rmul__(self, other): 

230 return N.dot(other, self) 

231 

232 def __imul__(self, other): 

233 self[:] = self * other 

234 return self 

235 

236 def __pow__(self, other): 

237 return matrix_power(self, other) 

238 

239 def __ipow__(self, other): 

240 self[:] = self ** other 

241 return self 

242 

243 def __rpow__(self, other): 

244 return NotImplemented 

245 

246 def _align(self, axis): 

247 """A convenience function for operations that need to preserve axis 

248 orientation. 

249 """ 

250 if axis is None: 

251 return self[0, 0] 

252 elif axis==0: 

253 return self 

254 elif axis==1: 

255 return self.transpose() 

256 else: 

257 raise ValueError("unsupported axis") 

258 

259 def _collapse(self, axis): 

260 """A convenience function for operations that want to collapse 

261 to a scalar like _align, but are using keepdims=True 

262 """ 

263 if axis is None: 

264 return self[0, 0] 

265 else: 

266 return self 

267 

268 # Necessary because base-class tolist expects dimension 

269 # reduction by x[0] 

270 def tolist(self): 

271 """ 

272 Return the matrix as a (possibly nested) list. 

273 

274 See `ndarray.tolist` for full documentation. 

275 

276 See Also 

277 -------- 

278 ndarray.tolist 

279 

280 Examples 

281 -------- 

282 >>> x = np.matrix(np.arange(12).reshape((3,4))); x 

283 matrix([[ 0, 1, 2, 3], 

284 [ 4, 5, 6, 7], 

285 [ 8, 9, 10, 11]]) 

286 >>> x.tolist() 

287 [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] 

288 

289 """ 

290 return self.__array__().tolist() 

291 

292 # To preserve orientation of result... 

293 def sum(self, axis=None, dtype=None, out=None): 

294 """ 

295 Returns the sum of the matrix elements, along the given axis. 

296 

297 Refer to `numpy.sum` for full documentation. 

298 

299 See Also 

300 -------- 

301 numpy.sum 

302 

303 Notes 

304 ----- 

305 This is the same as `ndarray.sum`, except that where an `ndarray` would 

306 be returned, a `matrix` object is returned instead. 

307 

308 Examples 

309 -------- 

310 >>> x = np.matrix([[1, 2], [4, 3]]) 

311 >>> x.sum() 

312 10 

313 >>> x.sum(axis=1) 

314 matrix([[3], 

315 [7]]) 

316 >>> x.sum(axis=1, dtype='float') 

317 matrix([[3.], 

318 [7.]]) 

319 >>> out = np.zeros((2, 1), dtype='float') 

320 >>> x.sum(axis=1, dtype='float', out=np.asmatrix(out)) 

321 matrix([[3.], 

322 [7.]]) 

323 

324 """ 

325 return N.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis) 

326 

327 

328 # To update docstring from array to matrix... 

329 def squeeze(self, axis=None): 

330 """ 

331 Return a possibly reshaped matrix. 

332 

333 Refer to `numpy.squeeze` for more documentation. 

334 

335 Parameters 

336 ---------- 

337 axis : None or int or tuple of ints, optional 

338 Selects a subset of the axes of length one in the shape. 

339 If an axis is selected with shape entry greater than one, 

340 an error is raised. 

341 

342 Returns 

343 ------- 

344 squeezed : matrix 

345 The matrix, but as a (1, N) matrix if it had shape (N, 1). 

346 

347 See Also 

348 -------- 

349 numpy.squeeze : related function 

350 

351 Notes 

352 ----- 

353 If `m` has a single column then that column is returned 

354 as the single row of a matrix. Otherwise `m` is returned. 

355 The returned matrix is always either `m` itself or a view into `m`. 

356 Supplying an axis keyword argument will not affect the returned matrix 

357 but it may cause an error to be raised. 

358 

359 Examples 

360 -------- 

361 >>> c = np.matrix([[1], [2]]) 

362 >>> c 

363 matrix([[1], 

364 [2]]) 

365 >>> c.squeeze() 

366 matrix([[1, 2]]) 

367 >>> r = c.T 

368 >>> r 

369 matrix([[1, 2]]) 

370 >>> r.squeeze() 

371 matrix([[1, 2]]) 

372 >>> m = np.matrix([[1, 2], [3, 4]]) 

373 >>> m.squeeze() 

374 matrix([[1, 2], 

375 [3, 4]]) 

376 

377 """ 

378 return N.ndarray.squeeze(self, axis=axis) 

379 

380 

381 # To update docstring from array to matrix... 

382 def flatten(self, order='C'): 

383 """ 

384 Return a flattened copy of the matrix. 

385 

386 All `N` elements of the matrix are placed into a single row. 

387 

388 Parameters 

389 ---------- 

390 order : {'C', 'F', 'A', 'K'}, optional 

391 'C' means to flatten in row-major (C-style) order. 'F' means to 

392 flatten in column-major (Fortran-style) order. 'A' means to 

393 flatten in column-major order if `m` is Fortran *contiguous* in 

394 memory, row-major order otherwise. 'K' means to flatten `m` in 

395 the order the elements occur in memory. The default is 'C'. 

396 

397 Returns 

398 ------- 

399 y : matrix 

400 A copy of the matrix, flattened to a `(1, N)` matrix where `N` 

401 is the number of elements in the original matrix. 

402 

403 See Also 

404 -------- 

405 ravel : Return a flattened array. 

406 flat : A 1-D flat iterator over the matrix. 

407 

408 Examples 

409 -------- 

410 >>> m = np.matrix([[1,2], [3,4]]) 

411 >>> m.flatten() 

412 matrix([[1, 2, 3, 4]]) 

413 >>> m.flatten('F') 

414 matrix([[1, 3, 2, 4]]) 

415 

416 """ 

417 return N.ndarray.flatten(self, order=order) 

418 

419 def mean(self, axis=None, dtype=None, out=None): 

420 """ 

421 Returns the average of the matrix elements along the given axis. 

422 

423 Refer to `numpy.mean` for full documentation. 

424 

425 See Also 

426 -------- 

427 numpy.mean 

428 

429 Notes 

430 ----- 

431 Same as `ndarray.mean` except that, where that returns an `ndarray`, 

432 this returns a `matrix` object. 

433 

434 Examples 

435 -------- 

436 >>> x = np.matrix(np.arange(12).reshape((3, 4))) 

437 >>> x 

438 matrix([[ 0, 1, 2, 3], 

439 [ 4, 5, 6, 7], 

440 [ 8, 9, 10, 11]]) 

441 >>> x.mean() 

442 5.5 

443 >>> x.mean(0) 

444 matrix([[4., 5., 6., 7.]]) 

445 >>> x.mean(1) 

446 matrix([[ 1.5], 

447 [ 5.5], 

448 [ 9.5]]) 

449 

450 """ 

451 return N.ndarray.mean(self, axis, dtype, out, keepdims=True)._collapse(axis) 

452 

453 def std(self, axis=None, dtype=None, out=None, ddof=0): 

454 """ 

455 Return the standard deviation of the array elements along the given axis. 

456 

457 Refer to `numpy.std` for full documentation. 

458 

459 See Also 

460 -------- 

461 numpy.std 

462 

463 Notes 

464 ----- 

465 This is the same as `ndarray.std`, except that where an `ndarray` would 

466 be returned, a `matrix` object is returned instead. 

467 

468 Examples 

469 -------- 

470 >>> x = np.matrix(np.arange(12).reshape((3, 4))) 

471 >>> x 

472 matrix([[ 0, 1, 2, 3], 

473 [ 4, 5, 6, 7], 

474 [ 8, 9, 10, 11]]) 

475 >>> x.std() 

476 3.4520525295346629 # may vary 

477 >>> x.std(0) 

478 matrix([[ 3.26598632, 3.26598632, 3.26598632, 3.26598632]]) # may vary 

479 >>> x.std(1) 

480 matrix([[ 1.11803399], 

481 [ 1.11803399], 

482 [ 1.11803399]]) 

483 

484 """ 

485 return N.ndarray.std(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis) 

486 

487 def var(self, axis=None, dtype=None, out=None, ddof=0): 

488 """ 

489 Returns the variance of the matrix elements, along the given axis. 

490 

491 Refer to `numpy.var` for full documentation. 

492 

493 See Also 

494 -------- 

495 numpy.var 

496 

497 Notes 

498 ----- 

499 This is the same as `ndarray.var`, except that where an `ndarray` would 

500 be returned, a `matrix` object is returned instead. 

501 

502 Examples 

503 -------- 

504 >>> x = np.matrix(np.arange(12).reshape((3, 4))) 

505 >>> x 

506 matrix([[ 0, 1, 2, 3], 

507 [ 4, 5, 6, 7], 

508 [ 8, 9, 10, 11]]) 

509 >>> x.var() 

510 11.916666666666666 

511 >>> x.var(0) 

512 matrix([[ 10.66666667, 10.66666667, 10.66666667, 10.66666667]]) # may vary 

513 >>> x.var(1) 

514 matrix([[1.25], 

515 [1.25], 

516 [1.25]]) 

517 

518 """ 

519 return N.ndarray.var(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis) 

520 

521 def prod(self, axis=None, dtype=None, out=None): 

522 """ 

523 Return the product of the array elements over the given axis. 

524 

525 Refer to `prod` for full documentation. 

526 

527 See Also 

528 -------- 

529 prod, ndarray.prod 

530 

531 Notes 

532 ----- 

533 Same as `ndarray.prod`, except, where that returns an `ndarray`, this 

534 returns a `matrix` object instead. 

535 

536 Examples 

537 -------- 

538 >>> x = np.matrix(np.arange(12).reshape((3,4))); x 

539 matrix([[ 0, 1, 2, 3], 

540 [ 4, 5, 6, 7], 

541 [ 8, 9, 10, 11]]) 

542 >>> x.prod() 

543 0 

544 >>> x.prod(0) 

545 matrix([[ 0, 45, 120, 231]]) 

546 >>> x.prod(1) 

547 matrix([[ 0], 

548 [ 840], 

549 [7920]]) 

550 

551 """ 

552 return N.ndarray.prod(self, axis, dtype, out, keepdims=True)._collapse(axis) 

553 

554 def any(self, axis=None, out=None): 

555 """ 

556 Test whether any array element along a given axis evaluates to True. 

557 

558 Refer to `numpy.any` for full documentation. 

559 

560 Parameters 

561 ---------- 

562 axis : int, optional 

563 Axis along which logical OR is performed 

564 out : ndarray, optional 

565 Output to existing array instead of creating new one, must have 

566 same shape as expected output 

567 

568 Returns 

569 ------- 

570 any : bool, ndarray 

571 Returns a single bool if `axis` is ``None``; otherwise, 

572 returns `ndarray` 

573 

574 """ 

575 return N.ndarray.any(self, axis, out, keepdims=True)._collapse(axis) 

576 

577 def all(self, axis=None, out=None): 

578 """ 

579 Test whether all matrix elements along a given axis evaluate to True. 

580 

581 Parameters 

582 ---------- 

583 See `numpy.all` for complete descriptions 

584 

585 See Also 

586 -------- 

587 numpy.all 

588 

589 Notes 

590 ----- 

591 This is the same as `ndarray.all`, but it returns a `matrix` object. 

592 

593 Examples 

594 -------- 

595 >>> x = np.matrix(np.arange(12).reshape((3,4))); x 

596 matrix([[ 0, 1, 2, 3], 

597 [ 4, 5, 6, 7], 

598 [ 8, 9, 10, 11]]) 

599 >>> y = x[0]; y 

600 matrix([[0, 1, 2, 3]]) 

601 >>> (x == y) 

602 matrix([[ True, True, True, True], 

603 [False, False, False, False], 

604 [False, False, False, False]]) 

605 >>> (x == y).all() 

606 False 

607 >>> (x == y).all(0) 

608 matrix([[False, False, False, False]]) 

609 >>> (x == y).all(1) 

610 matrix([[ True], 

611 [False], 

612 [False]]) 

613 

614 """ 

615 return N.ndarray.all(self, axis, out, keepdims=True)._collapse(axis) 

616 

617 def max(self, axis=None, out=None): 

618 """ 

619 Return the maximum value along an axis. 

620 

621 Parameters 

622 ---------- 

623 See `amax` for complete descriptions 

624 

625 See Also 

626 -------- 

627 amax, ndarray.max 

628 

629 Notes 

630 ----- 

631 This is the same as `ndarray.max`, but returns a `matrix` object 

632 where `ndarray.max` would return an ndarray. 

633 

634 Examples 

635 -------- 

636 >>> x = np.matrix(np.arange(12).reshape((3,4))); x 

637 matrix([[ 0, 1, 2, 3], 

638 [ 4, 5, 6, 7], 

639 [ 8, 9, 10, 11]]) 

640 >>> x.max() 

641 11 

642 >>> x.max(0) 

643 matrix([[ 8, 9, 10, 11]]) 

644 >>> x.max(1) 

645 matrix([[ 3], 

646 [ 7], 

647 [11]]) 

648 

649 """ 

650 return N.ndarray.max(self, axis, out, keepdims=True)._collapse(axis) 

651 

652 def argmax(self, axis=None, out=None): 

653 """ 

654 Indexes of the maximum values along an axis. 

655 

656 Return the indexes of the first occurrences of the maximum values 

657 along the specified axis. If axis is None, the index is for the 

658 flattened matrix. 

659 

660 Parameters 

661 ---------- 

662 See `numpy.argmax` for complete descriptions 

663 

664 See Also 

665 -------- 

666 numpy.argmax 

667 

668 Notes 

669 ----- 

670 This is the same as `ndarray.argmax`, but returns a `matrix` object 

671 where `ndarray.argmax` would return an `ndarray`. 

672 

673 Examples 

674 -------- 

675 >>> x = np.matrix(np.arange(12).reshape((3,4))); x 

676 matrix([[ 0, 1, 2, 3], 

677 [ 4, 5, 6, 7], 

678 [ 8, 9, 10, 11]]) 

679 >>> x.argmax() 

680 11 

681 >>> x.argmax(0) 

682 matrix([[2, 2, 2, 2]]) 

683 >>> x.argmax(1) 

684 matrix([[3], 

685 [3], 

686 [3]]) 

687 

688 """ 

689 return N.ndarray.argmax(self, axis, out)._align(axis) 

690 

691 def min(self, axis=None, out=None): 

692 """ 

693 Return the minimum value along an axis. 

694 

695 Parameters 

696 ---------- 

697 See `amin` for complete descriptions. 

698 

699 See Also 

700 -------- 

701 amin, ndarray.min 

702 

703 Notes 

704 ----- 

705 This is the same as `ndarray.min`, but returns a `matrix` object 

706 where `ndarray.min` would return an ndarray. 

707 

708 Examples 

709 -------- 

710 >>> x = -np.matrix(np.arange(12).reshape((3,4))); x 

711 matrix([[ 0, -1, -2, -3], 

712 [ -4, -5, -6, -7], 

713 [ -8, -9, -10, -11]]) 

714 >>> x.min() 

715 -11 

716 >>> x.min(0) 

717 matrix([[ -8, -9, -10, -11]]) 

718 >>> x.min(1) 

719 matrix([[ -3], 

720 [ -7], 

721 [-11]]) 

722 

723 """ 

724 return N.ndarray.min(self, axis, out, keepdims=True)._collapse(axis) 

725 

726 def argmin(self, axis=None, out=None): 

727 """ 

728 Indexes of the minimum values along an axis. 

729 

730 Return the indexes of the first occurrences of the minimum values 

731 along the specified axis. If axis is None, the index is for the 

732 flattened matrix. 

733 

734 Parameters 

735 ---------- 

736 See `numpy.argmin` for complete descriptions. 

737 

738 See Also 

739 -------- 

740 numpy.argmin 

741 

742 Notes 

743 ----- 

744 This is the same as `ndarray.argmin`, but returns a `matrix` object 

745 where `ndarray.argmin` would return an `ndarray`. 

746 

747 Examples 

748 -------- 

749 >>> x = -np.matrix(np.arange(12).reshape((3,4))); x 

750 matrix([[ 0, -1, -2, -3], 

751 [ -4, -5, -6, -7], 

752 [ -8, -9, -10, -11]]) 

753 >>> x.argmin() 

754 11 

755 >>> x.argmin(0) 

756 matrix([[2, 2, 2, 2]]) 

757 >>> x.argmin(1) 

758 matrix([[3], 

759 [3], 

760 [3]]) 

761 

762 """ 

763 return N.ndarray.argmin(self, axis, out)._align(axis) 

764 

765 def ptp(self, axis=None, out=None): 

766 """ 

767 Peak-to-peak (maximum - minimum) value along the given axis. 

768 

769 Refer to `numpy.ptp` for full documentation. 

770 

771 See Also 

772 -------- 

773 numpy.ptp 

774 

775 Notes 

776 ----- 

777 Same as `ndarray.ptp`, except, where that would return an `ndarray` object, 

778 this returns a `matrix` object. 

779 

780 Examples 

781 -------- 

782 >>> x = np.matrix(np.arange(12).reshape((3,4))); x 

783 matrix([[ 0, 1, 2, 3], 

784 [ 4, 5, 6, 7], 

785 [ 8, 9, 10, 11]]) 

786 >>> x.ptp() 

787 11 

788 >>> x.ptp(0) 

789 matrix([[8, 8, 8, 8]]) 

790 >>> x.ptp(1) 

791 matrix([[3], 

792 [3], 

793 [3]]) 

794 

795 """ 

796 return N.ptp(self, axis, out)._align(axis) 

797 

798 @property 

799 def I(self): 

800 """ 

801 Returns the (multiplicative) inverse of invertible `self`. 

802 

803 Parameters 

804 ---------- 

805 None 

806 

807 Returns 

808 ------- 

809 ret : matrix object 

810 If `self` is non-singular, `ret` is such that ``ret * self`` == 

811 ``self * ret`` == ``np.matrix(np.eye(self[0,:].size))`` all return 

812 ``True``. 

813 

814 Raises 

815 ------ 

816 numpy.linalg.LinAlgError: Singular matrix 

817 If `self` is singular. 

818 

819 See Also 

820 -------- 

821 linalg.inv 

822 

823 Examples 

824 -------- 

825 >>> m = np.matrix('[1, 2; 3, 4]'); m 

826 matrix([[1, 2], 

827 [3, 4]]) 

828 >>> m.getI() 

829 matrix([[-2. , 1. ], 

830 [ 1.5, -0.5]]) 

831 >>> m.getI() * m 

832 matrix([[ 1., 0.], # may vary 

833 [ 0., 1.]]) 

834 

835 """ 

836 M, N = self.shape 

837 if M == N: 

838 from numpy.linalg import inv as func 

839 else: 

840 from numpy.linalg import pinv as func 

841 return asmatrix(func(self)) 

842 

843 @property 

844 def A(self): 

845 """ 

846 Return `self` as an `ndarray` object. 

847 

848 Equivalent to ``np.asarray(self)``. 

849 

850 Parameters 

851 ---------- 

852 None 

853 

854 Returns 

855 ------- 

856 ret : ndarray 

857 `self` as an `ndarray` 

858 

859 Examples 

860 -------- 

861 >>> x = np.matrix(np.arange(12).reshape((3,4))); x 

862 matrix([[ 0, 1, 2, 3], 

863 [ 4, 5, 6, 7], 

864 [ 8, 9, 10, 11]]) 

865 >>> x.getA() 

866 array([[ 0, 1, 2, 3], 

867 [ 4, 5, 6, 7], 

868 [ 8, 9, 10, 11]]) 

869 

870 """ 

871 return self.__array__() 

872 

873 @property 

874 def A1(self): 

875 """ 

876 Return `self` as a flattened `ndarray`. 

877 

878 Equivalent to ``np.asarray(x).ravel()`` 

879 

880 Parameters 

881 ---------- 

882 None 

883 

884 Returns 

885 ------- 

886 ret : ndarray 

887 `self`, 1-D, as an `ndarray` 

888 

889 Examples 

890 -------- 

891 >>> x = np.matrix(np.arange(12).reshape((3,4))); x 

892 matrix([[ 0, 1, 2, 3], 

893 [ 4, 5, 6, 7], 

894 [ 8, 9, 10, 11]]) 

895 >>> x.getA1() 

896 array([ 0, 1, 2, ..., 9, 10, 11]) 

897 

898 

899 """ 

900 return self.__array__().ravel() 

901 

902 

903 def ravel(self, order='C'): 

904 """ 

905 Return a flattened matrix. 

906 

907 Refer to `numpy.ravel` for more documentation. 

908 

909 Parameters 

910 ---------- 

911 order : {'C', 'F', 'A', 'K'}, optional 

912 The elements of `m` are read using this index order. 'C' means to 

913 index the elements in C-like order, with the last axis index 

914 changing fastest, back to the first axis index changing slowest. 

915 'F' means to index the elements in Fortran-like index order, with 

916 the first index changing fastest, and the last index changing 

917 slowest. Note that the 'C' and 'F' options take no account of the 

918 memory layout of the underlying array, and only refer to the order 

919 of axis indexing. 'A' means to read the elements in Fortran-like 

920 index order if `m` is Fortran *contiguous* in memory, C-like order 

921 otherwise. 'K' means to read the elements in the order they occur 

922 in memory, except for reversing the data when strides are negative. 

923 By default, 'C' index order is used. 

924 

925 Returns 

926 ------- 

927 ret : matrix 

928 Return the matrix flattened to shape `(1, N)` where `N` 

929 is the number of elements in the original matrix. 

930 A copy is made only if necessary. 

931 

932 See Also 

933 -------- 

934 matrix.flatten : returns a similar output matrix but always a copy 

935 matrix.flat : a flat iterator on the array. 

936 numpy.ravel : related function which returns an ndarray 

937 

938 """ 

939 return N.ndarray.ravel(self, order=order) 

940 

941 @property 

942 def T(self): 

943 """ 

944 Returns the transpose of the matrix. 

945 

946 Does *not* conjugate! For the complex conjugate transpose, use ``.H``. 

947 

948 Parameters 

949 ---------- 

950 None 

951 

952 Returns 

953 ------- 

954 ret : matrix object 

955 The (non-conjugated) transpose of the matrix. 

956 

957 See Also 

958 -------- 

959 transpose, getH 

960 

961 Examples 

962 -------- 

963 >>> m = np.matrix('[1, 2; 3, 4]') 

964 >>> m 

965 matrix([[1, 2], 

966 [3, 4]]) 

967 >>> m.getT() 

968 matrix([[1, 3], 

969 [2, 4]]) 

970 

971 """ 

972 return self.transpose() 

973 

974 @property 

975 def H(self): 

976 """ 

977 Returns the (complex) conjugate transpose of `self`. 

978 

979 Equivalent to ``np.transpose(self)`` if `self` is real-valued. 

980 

981 Parameters 

982 ---------- 

983 None 

984 

985 Returns 

986 ------- 

987 ret : matrix object 

988 complex conjugate transpose of `self` 

989 

990 Examples 

991 -------- 

992 >>> x = np.matrix(np.arange(12).reshape((3,4))) 

993 >>> z = x - 1j*x; z 

994 matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j], 

995 [ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j], 

996 [ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]]) 

997 >>> z.getH() 

998 matrix([[ 0. -0.j, 4. +4.j, 8. +8.j], 

999 [ 1. +1.j, 5. +5.j, 9. +9.j], 

1000 [ 2. +2.j, 6. +6.j, 10.+10.j], 

1001 [ 3. +3.j, 7. +7.j, 11.+11.j]]) 

1002 

1003 """ 

1004 if issubclass(self.dtype.type, N.complexfloating): 

1005 return self.transpose().conjugate() 

1006 else: 

1007 return self.transpose() 

1008 

1009 # kept for compatibility 

1010 getT = T.fget 

1011 getA = A.fget 

1012 getA1 = A1.fget 

1013 getH = H.fget 

1014 getI = I.fget 

1015 

1016def _from_string(str, gdict, ldict): 

1017 rows = str.split(';') 

1018 rowtup = [] 

1019 for row in rows: 

1020 trow = row.split(',') 

1021 newrow = [] 

1022 for x in trow: 

1023 newrow.extend(x.split()) 

1024 trow = newrow 

1025 coltup = [] 

1026 for col in trow: 

1027 col = col.strip() 

1028 try: 

1029 thismat = ldict[col] 

1030 except KeyError: 

1031 try: 

1032 thismat = gdict[col] 

1033 except KeyError as e: 

1034 raise NameError(f"name {col!r} is not defined") from None 

1035 

1036 coltup.append(thismat) 

1037 rowtup.append(concatenate(coltup, axis=-1)) 

1038 return concatenate(rowtup, axis=0) 

1039 

1040 

1041@set_module('numpy') 

1042def bmat(obj, ldict=None, gdict=None): 

1043 """ 

1044 Build a matrix object from a string, nested sequence, or array. 

1045 

1046 Parameters 

1047 ---------- 

1048 obj : str or array_like 

1049 Input data. If a string, variables in the current scope may be 

1050 referenced by name. 

1051 ldict : dict, optional 

1052 A dictionary that replaces local operands in current frame. 

1053 Ignored if `obj` is not a string or `gdict` is None. 

1054 gdict : dict, optional 

1055 A dictionary that replaces global operands in current frame. 

1056 Ignored if `obj` is not a string. 

1057 

1058 Returns 

1059 ------- 

1060 out : matrix 

1061 Returns a matrix object, which is a specialized 2-D array. 

1062 

1063 See Also 

1064 -------- 

1065 block : 

1066 A generalization of this function for N-d arrays, that returns normal 

1067 ndarrays. 

1068 

1069 Examples 

1070 -------- 

1071 >>> import numpy as np 

1072 >>> A = np.asmatrix('1 1; 1 1') 

1073 >>> B = np.asmatrix('2 2; 2 2') 

1074 >>> C = np.asmatrix('3 4; 5 6') 

1075 >>> D = np.asmatrix('7 8; 9 0') 

1076 

1077 All the following expressions construct the same block matrix: 

1078 

1079 >>> np.bmat([[A, B], [C, D]]) 

1080 matrix([[1, 1, 2, 2], 

1081 [1, 1, 2, 2], 

1082 [3, 4, 7, 8], 

1083 [5, 6, 9, 0]]) 

1084 >>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]]) 

1085 matrix([[1, 1, 2, 2], 

1086 [1, 1, 2, 2], 

1087 [3, 4, 7, 8], 

1088 [5, 6, 9, 0]]) 

1089 >>> np.bmat('A,B; C,D') 

1090 matrix([[1, 1, 2, 2], 

1091 [1, 1, 2, 2], 

1092 [3, 4, 7, 8], 

1093 [5, 6, 9, 0]]) 

1094 

1095 """ 

1096 if isinstance(obj, str): 

1097 if gdict is None: 

1098 # get previous frame 

1099 frame = sys._getframe().f_back 

1100 glob_dict = frame.f_globals 

1101 loc_dict = frame.f_locals 

1102 else: 

1103 glob_dict = gdict 

1104 loc_dict = ldict 

1105 

1106 return matrix(_from_string(obj, glob_dict, loc_dict)) 

1107 

1108 if isinstance(obj, (tuple, list)): 

1109 # [[A,B],[C,D]] 

1110 arr_rows = [] 

1111 for row in obj: 

1112 if isinstance(row, N.ndarray): # not 2-d 

1113 return matrix(concatenate(obj, axis=-1)) 

1114 else: 

1115 arr_rows.append(concatenate(row, axis=-1)) 

1116 return matrix(concatenate(arr_rows, axis=0)) 

1117 if isinstance(obj, N.ndarray): 

1118 return matrix(obj)