“Converting” Numpy arrays to Matlab and vice versa

后端 未结 6 1403
孤独总比滥情好
孤独总比滥情好 2020-11-30 00:27

I am looking for a way to pass NumPy arrays to Matlab.

I\'ve managed to do this by storing the array into an image using scipy.misc.imsave and then loa

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 01:02

    Not sure if it counts as "simpler" but I found a solution to move data from a numpy arrray created in a python script which is called by matlab quite fast:

    dump_reader.py (python source):

    import numpy
    
    def matlab_test2():
        np_a    = numpy.random.uniform(low = 0.0, high = 30000.0, size = (1000,1000))
        return np_a
    

    dump_read.m (matlab script):

    clear classes
    mod = py.importlib.import_module('dump_reader');
    py.importlib.reload(mod);
    
    if count(py.sys.path,'') == 0
        insert(py.sys.path,int32(0),'');
    end
    
    tic
    A = py.dump_reader.matlab_test2();
    toc
    shape = cellfun(@int64,cell(A.shape));
    ls = py.array.array('d',A.flatten('F').tolist());
    p = double(ls);
    toc
    C = reshape(p,shape);
    toc
    

    It relies on the fact that matlabs double seems be working efficiently on arrays compared to cells/matrices. Second trick is to pass the data to matlabs double in an efficient way (via pythons native array.array).

    P.S. sorry for necroposting but I struggled a lot with its and this topic was one of the closest hits. Maybe it helps someone to shorten the time of struggling.

    P.P.S. tested with Matlab R2016b + python 3.5.4 (64bit)

提交回复
热议问题