python - Issue with porting a 3d matrix from matlab to python
问题描述
I'm trying to port some code from a matlab script to python and i run on a 3d matrix. I'm trying to implement it on python but i have encountered a strange behavior in my python code. I'm presenting here a simplified version of my problem:
(It has to be a matrix and not an array since in the original problem it has to store symbolic expressions)
Matlab code, it creates a series of triangular arrays of ixi size , where i = 1:n :
n = 3;
f = zeros(n+1,n+1,n+1);
for m = 1:n
for i = 1:m+1
for j = 1:m+1 -i +1
f(i,j,m+1) = i*j*m;
end
end
end
My python code :
n = 3;
f = [[[0 for k in range(n+1)] for j in range(n+1)] for i in range(n+1)]
for m in range(n):
for i in range(m+2):
for j in range(m+2-i):
f[i][j][m+1] = (i+1)*(j+1)*(m+1);
Matlab outout for the last 2 matrices:
f(:,:,3) = f(:,:,4) =
2 4 6 0 3 6 9 12
4 8 0 0 6 12 18 0
6 0 0 0 9 18 0 0
0 0 0 0 12 0 0 0
Python output for the last 2 matrices:
[[0, 0, 6, 9], [0, 0, 0, 18], [0, 0, 0, 0], [0, 0, 0, 0]],
[[0, 0, 0, 12], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]
I have checked that the number of iterations are the same in both codes. i also have checked that the indexes have the correct values in each iteration. For example: Matlab m,i,j = (1,1,1) equals with Python m,i,j = (0,0,0)
解决方案
Well it seems swtching the 1st and 3d index solved the issue. The correct python code is:
n = 3;
f = [[[0 for k in range(n+1)] for j in range(n+1)] for i in range(n+1)]
for m in range(n):
for i in range(m+2):
for j in range(m+2-i):
f[m+1][i][j] = (i+1)*(j+1)*(m+1);
and the output confirms it:
[[2, 4, 6, 0], [4, 8, 0, 0], [6, 0, 0, 0], [0, 0, 0, 0]],
[[3, 6, 9, 12], [6, 12, 18, 0], [9, 18, 0, 0], [12, 0, 0, 0]]]
推荐阅读
- javascript - onclick 超文本链接显示选择选项
- javascript - 故事书的迁移
- spring - 带有 Hystrix 的 Spring 微服务 - 仅回退返回/抛出异常
- c - 如何在 C 项目中包含 ThrowTheSwitch/Unity?
- c - 如何读取旋转编码器输入
- php - laravel 6路由返回404未找到
- safari - 我的 AMP 页面中的 QuotaExceededError 仅在 Safari 浏览器中
- google-bigquery - 将 Grafana 与 BigQuery 数据源一起使用时出现问题
- solr - 他们是一种根据同一调用的先前分数结果过滤 solr 结果的方法吗?
- c++ - 在 0x5914F3BE (ucrtbased.dll) 处引发异常