首页 > 解决方案 > 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)

标签: pythonmatlabmatrix

解决方案


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]]]

推荐阅读