gpt4 book ai didi

python - 将代码 matlab 转换为 python numpy

转载 作者:太空宇宙 更新时间:2023-11-04 05:24:30 25 4
gpt4 key购买 nike

我不懂matlab编程,我只懂python编码...

here my matrix want to solve

Matlab代码:

 x = ones(3,1).
con = [0.505868045540458,0.523598775598299].
series = [1,2,3]
for j = 1:2
#here stuck to translate Python code#
x = [x cos(con(j)*series)' sin(con(j)*series)'];
end

结果:

1.0000    0.8748    0.4846    0.8660    0.5000
1.0000 0.5304 0.8478 0.5000 0.8660
1.0000 0.0532 0.9986 -0.0000 1.0000

谁能帮帮我,请问如何解决这个问题...问候!

最佳答案

我在 Ipython session 中的娱乐(首先在 Octave session 中测试了您的代码):

In [649]: con = np.array([0.505868, 0.5235897])
In [650]: series = np.array([1,2,3])
In [651]: x = [np.ones((3,))]
In [652]: for j in range(2):
...: x.extend([np.cos(con[j]*series), np.sin(con[j]*series)])
...:
In [653]: x
Out[653]:
[array([ 1., 1., 1.]),
array([ 0.8747542 , 0.53038982, 0.05316725]),
array([ 0.48456691, 0.84775388, 0.99858562]),
array([ 8.66029942e-01, 5.00015719e-01, 2.72267949e-05]),
array([ 0.49999214, 0.86601633, 1. ])]
In [654]: np.array(x).T
Out[654]:
array([[ 1.00000000e+00, 8.74754200e-01, 4.84566909e-01,
8.66029942e-01, 4.99992140e-01],
[ 1.00000000e+00, 5.30389821e-01, 8.47753878e-01,
5.00015719e-01, 8.66016328e-01],
[ 1.00000000e+00, 5.31672464e-02, 9.98585622e-01,
2.72267949e-05, 1.00000000e+00]])

在MATLAB中

x = [x cos(...) sin(...)]

更接近于

x = np.concatenate([x, cos(...), sin(...)], axis=?)

但在 numpy 列表中追加(或在本例中为扩展)更快。我只需将 x 初始化为适当的列表即可。

==================

我可以在没有循环的情况下得到相同的值

In [663]: y = con[:,None]*series
In [664]: [np.cos(y), np.sin(y)]
Out[664]:
[array([[ 8.74754200e-01, 5.30389821e-01, 5.31672464e-02],
[ 8.66029942e-01, 5.00015719e-01, 2.72267949e-05]]),
array([[ 0.48456691, 0.84775388, 0.99858562],
[ 0.49999214, 0.86601633, 1. ]])]

但是将它们重新排列成迭代产生的顺序有点痛苦,[1, cos, sin, cos, sin]

关于python - 将代码 matlab 转换为 python numpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39285004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com