fork download
  1. import numpy as np
  2.  
  3. # Example 1: (2, 2, 3) @ (2, 3, 2) → (2, 2, 2)
  4. a = np.array([1,2,3,4,5,6,7,8,9,10,11,12], dtype=np.float32).reshape(2, 2, 3, order='F')
  5. b = np.array([1,2,3,4,5,6,7,8,9,10,11,12], dtype=np.float32).reshape(2, 3, 2, order='F')
  6.  
  7. result1 = np.matmul(a, b)
  8. print("Example 1 Shape:", result1.shape)
  9. print(result1.flatten(order='F'))
  10.  
  11. # Example 2: Broadcasting (3, 1, 2, 3) @ (1, 4, 3, 2) → (3, 4, 2, 2)
  12. c = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
  13. dtype=np.float32).reshape(3,1,2,3, order='F')
  14. d = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
  15. dtype=np.float32).reshape(1, 4, 3, 2, order='F')
  16.  
  17. result2 = np.matmul(c, d)
  18. print("Example 2 Shape:", result2.shape)
  19. print(result2.flatten(order='F'))
  20.  
  21.  
  22.  
  23. # data = np.arange(1, 25, dtype=np.float32)
  24.  
  25. # # reshape using order='F' to match column-major layout
  26. # mat = np.reshape(data, (2, 3, 4), order='F')
  27. # vec = np.array([1., 2., 3.], dtype=np.float32)
  28.  
  29. # # perform matmul (NumPy handles broadcasting automatically)
  30. # result = np.matmul(vec, mat) # equivalent to Tensor::matmul(vec, mat)
  31.  
  32. # print("mat shape:", mat.shape)
  33. # print("vec shape:", vec.shape)
  34. # print("result shape:", result.shape)
  35. # print(result)
  36.  
  37.  
  38. # vec2 = np.array([1., 2., 3., 4.], dtype=np.float32)
  39. # mat2 = np.reshape(np.arange(1, 25, dtype=np.float32), (2, 3, 4), order='F')
  40. # result = np.matmul(mat2, vec2)
  41.  
  42. # print(result.shape) # (2, 3)
  43. # print(result)
  44.  
  45.  
Success #stdin #stdout 0.08s 23524KB
stdin
Standard input is empty
stdout
('Example 1 Shape:', (2, 2, 2))
[ 61.  88.  79. 112. 151. 196. 205. 256.]
('Example 2 Shape:', (3, 4, 2, 2))
[153. 168. 183. 174. 192. 210. 195. 216. 237. 216. 240. 264. 198. 213.
 228. 228. 246. 264. 258. 279. 300. 288. 312. 336. 405. 456. 507. 426.
 480. 534. 447. 504. 561. 468. 528. 588. 558. 609. 660. 588. 642. 696.
 618. 675. 732. 648. 708. 768.]