You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Numpy生成与MATLAB一致的D变量?逐元素乘法问题

Fixing NumPy Code to Match MATLAB's bsxfun(@times) Result

Let's break down why your current NumPy code isn't matching MATLAB's output, then adjust it to get the correct D array.

Understanding the MATLAB Behavior

First, let's recap what MATLAB is doing:

  • A is a 3x3 matrix.
  • C gets reshaped to 1x3x2 (a 3D array with 1 row, 3 columns, 2 slices).
  • bsxfun(@times, A, C) automatically broadcasts the arrays to compatible dimensions:
    • A (3x3) is expanded to a 3x3x2 array (repeating its values across the 3rd dimension twice).
    • C (1x3x2) is expanded to a 3x3x2 array (repeating its values across the 1st dimension three times).
    • Element-wise multiplication happens, resulting in a 3x3x2 array where:
      • D(:,:,1) is A multiplied column-wise by [100, 10, 1]
      • D(:,:,2) is A multiplied column-wise by [1, 0.1, 0.01]

What's Wrong with the Current NumPy Code?

Your current code uses C.T, which transposes the (1,3,2) array into (2,3,1). When multiplied with A (3x3), NumPy broadcasts to a (2,3,3) array—this flips the dimensions compared to MATLAB's output, leading to mismatched values.

Corrected NumPy Code

To replicate MATLAB's broadcasting logic, we need to align the dimensions properly. We'll expand A to have a singleton 3rd dimension (so it matches the 3rd dimension of C), then perform element-wise multiplication:

import numpy as np

A = np.array([[1,2,3],[4,5,6],[7,8,9]])
# C matches the reshaped MATLAB version: shape (1, 3, 2)
C = np.array([[[100, 1], [10, 0.1], [1, 0.01]]])

# Expand A to shape (3,3,1) to broadcast with C (1,3,2)
D = A[:, :, np.newaxis] * C

Verifying the Result

Let's check the output:

  • D[:,:,0] will be:
    [[100.  20.   3.]
     [400.  50.   6.]
     [700.  80.   9.]]
    
  • D[:,:,1] will be:
    [[1.    0.2   0.03]
     [4.    0.5   0.06]
     [7.    0.8   0.09]]
    

This exactly matches the MATLAB output you provided.

Alternative Approach (Using Reshape for Clarity)

If you prefer to start with the original C values (before MATLAB's reshape), you can do this:

import numpy as np

A = np.array([[1,2,3],[4,5,6],[7,8,9]])
# Original C from MATLAB: 3x2 array
C_original = np.array([[100, 1], [10, 0.1], [1, 0.01]])
# Reshape to match MATLAB's (1,3,2)
C = C_original.reshape(1, 3, 2)

D = A[:, :, np.newaxis] * C

This gives the same correct result.

内容的提问来源于stack exchange,提问作者rafidude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:14:04