1
votes

I'm trying to multiply some arrays together but can't seem to figure out how to do it. I'm translating some linear algebra code from MatLab and can't seem to get it to work the same in Numpy due to Matlab using column-major indexing and Python using row-major indexing.

I've managed to get the matrices to multiply, but I've not managed to get the same result as the one in Matlab.

I have three arrays:

a.shape = 40x40 in Python, 40x40 in Matlab, zeroes array
b.shape = 40x21 in Python, 21x40 in Matlab, array with < 1 float values
c.shape = 31x40 in Python, 40x31 in Matlab, array with < 1 float values

The math I'm trying to copy from Matlab is:

    D = b*(a*c);
    disp(size(D));  % Size of D is 21x31

When I try and do the same with NumPy:

D = b @ (a @ c)

It obviously doesn't work since c is 31x40 and can't multiply with A (40x40).

I've managed to get the multiplication to actually work by using:

D = np.transpose(np.transpose(b) @ (a @ np.transpose(c)))

but the resulting D in Numpy is different from the one in Matlab, although the dimensions are correct (31x21).

If anyone has any ideas how to do this or even if it's not possible please let me know!

1
Axis 0 is rows in Python same as in Matlab. Don't confuse in memory ordering with indexing.Mad Physicist
@MadPhysicist so if I do it the same way as in Matlab it should work? I was looking at stackoverflow.com/questions/38789455/… and figured I had to change every single 3D array to the numpy syntaxPecans
You'd have to transpose a as well to get the same output. And if you're transposing everything, maybe you are defining your matrices wrong. You should preserve the shape they have in MATLAB, as MadPhysicist suggests.Cris Luengo
The Q&A you link discusses the difference in 3D arrays, matrices are indexed the same.Cris Luengo
c@a@b should produce a (31,21). Think A@B last of A pairs with 2nd to the last of Bhpaulj

1 Answers

0
votes

nope just run it with random numbers differences are limited to rounding errors

quick simple example to check correct matrix sizes:

import numpy as np
np.__version__ 
#'1.16.3'
a = np.ones([40,40])
b = np.ones([21,40])
c = np.ones([40,31])
#%%
a_mult_c = a @ c
a_mult_c.shape()
# (40, 31)
#%%
D = b @ a_mult_c
D.shape
# (21, 31)

for a detailed random number example load an run these numbers

https://jsonblob.com/c240c380-81a2-11e9-8287-ef9cd282f8ed

assuming you copy, paste and save it to 'matrixmult.json' matlab:

fid = fopen('matrixmult.json', 'r');
values = jsondecode(fread(fid, '*char')'));
fclose(fid);

python:

import numpy as np
np.__version__ 
# '1.16.3' 
import json
with open('matrixmult.json', 'r') as f:  # py > 3.6
    values = json.load(f)
a = np.asarray(values['a'])
b = np.asarray(values['b'])
c = np.asarray(values['c'])

D = b @ (a @ c)
D == np.asarray(values['D'])