【问题标题】:How to convert matlab code to python code?如何将matlab代码转换为python代码?
【发布时间】:2022-12-30 00:09:17
【问题描述】:

我需要将我的 Matlab 代码转换为 Python 代码。

实际上,我试过这个。我在下面收到错误代码。

由于将代码转换为python,因此在'H_sel'部分发生错误。

错误:SyntaxError:语法无效

# === matlab code ===
 % system-parameters
 Nt = 16;
 Nr = 16;

 % 1. conversion SNRdB to Linear
 SNRdB = 10;
 SNR= 10^(SNRdB/10);

 % 2. number to array
 Nr = 16;
 fully_Nr = (1:Nr);

 % 3. Rayleigh fading channel matrix
 H = sqrt(1/2)*(randn(Nr,Nt)+1j*randn(Nr,Nt));

 % 4. generate selected channel matrix
 H_sel=H((1:Nr),:);

 % 5. Selected channel capacity
 capacity=log2(det(eye(Nt)+SNR/Nt*(H_sel'*H_sel)));


 # === converted matlab code (python) ===
 # system-parameters
 import numpy as np
 Nt = 16
 Nr = 16
 
 # 1. conversion SNRdB to Linear
 SNRdB = 10
 SNR = 10 ** (SNRdB / 10)

 # 2. number to array
 Nr = 16
 fully_Nr = (np.arange(1,Nr+1))
 
 # 3. Rayleigh fading channel matrix (transmit, receive antennas)
 H = np.sqrt(1 / 2) * (np.random.randn(Nr,Nt) + 1j * np.random.randn(Nr,Nt))
 
 # 4. generate selected channel matrix (error line!!!!!!!)
 H_sel = H((np.arange(1,Nr+1)),:)
 
 # 5. Selected channel capacity
 capacity = np.log2(np.linalg.det(np.eye(Nt) + SNR / Nt * (np.transpose(H_sel) * H_sel)))
 print(capacity)

【问题讨论】:

  • Python 使用从零开始的索引,并使用方括号[] 进行索引/切片。 Matlab 使用基于一的索引和括号 () 进行索引/切片。切片语义也不同。 Python 切片不包括终点,而 Matlab 包括。翻译此代码时,您需要考虑这些差异(和其他差异)。
  • 具体来说,我猜你想要H_sel = H[:Nr,:]。此外,在 numpy 中,* 表示按元素相乘(相当于 Matlab 中的 .*)。在 numpy 中使用 np.dotnp.matmul@ 运算符进行矩阵乘法(dotmatmul/@ 具有不同的广播语义,但我认为它们在这里的工作方式相同)。
  • 感谢您的 cmets,其实我对 python 语言和 stack-overflow 平台并不熟悉。谢谢您的帮助。

标签: matlab


【解决方案1】:

尝试使用此工具将您的代码从 matlab 转换为 python 代码:https://github.com/ebranlard/matlab2python

【讨论】:

    猜你喜欢
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多