MATLAB to Python读取 [英] MATLAB to Python fread

查看:132
本文介绍了MATLAB to Python读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上想做的是将一些MATLAB代码转换为Python:

What I am basically trying to do is convert from some MATLAB code to Python:

MATLAB代码:

    for time = 100:model_times
        for i = 1:5
            indat = fread(fid,[48,40],'real*4');
            vort(:,:,i,time) = indat';
        end
    end

fid保留正在使用的文件路径(DAT文件). vort被预先分配为:vort = zeros(40,48,5,model_times). model_times是固定整数(例如100).

fid holds the file path (a DAT file) is being used. vort is a preallocated as: vort = zeros(40,48,5,model_times). model_times is a fixed integer (e.g. 100).

似乎正在发生的是,.dat文件数据以48x40矩阵的形式读取,然后在固定的i和时间(循环计数器)处插入预分配的阵列vort中.

What seems to be happening is that the .dat file data is being read in as a 48x40 matrix, then inserted into the preallocated array vort, at a fixed i and time (the loop counters).

我已经在Python中尝试过

I have attempted this in Python:

    for time in range(model_times):
        for i in range(5):
            vort[:,:,i,time] = np.fromfile(fid,np.float64)

我收到一个错误,指出"ValueError:操作数不能与形状(40,48)(6048000)一起广播".该错误发生在上面的Python代码的最后一行.我还尝试将.reshape((40,48,5,model_times))添加到有错误的行中,但收到另一个错误,指出"ValueError:新数组的总大小必须保持不变."

I receive an error that says, "ValueError: operands could not be broadcast together with shapes (40,48) (6048000)". The error occurs on the last line of Python code above. I have also tried adding .reshape((40,48,5,model_times)) to the line with the error, but receive another error that says "ValueError: total size of new array must be unchanged."

所以我的问题是,与MATLAB的"fread"等效的Python是什么,它可以处理多维数组?

So my question is, what is the Python equivalent to MATLAB's "fread", that can handle multidimensional arrays?

从1到10的比例,其中1个是初学者,而10个是经验丰富的老手,我大约是4岁.

On a scale from 1 to 10, with 1 being a total beginner and 10 being a seasoned veteran, I'm about a 4.

推荐答案

这也应该起作用.没有理由您无法一次完成所有操作:

This should work too. No reason you can't do it all in a single read:

vort = np.fromfile(fid, np.float64).reshape((model_times,5,48,40)).transpose()

您必须小心地将一维数组的形状调整为文件中数组索引的本机顺序(model_times,5,48,40),然后使用转置将索引重新排列为所需的顺序(40, 48,5,model_times).如果您尝试直接调整后者的形状,则会在错误的位置获取数据.

You have to be careful to reshape the 1-D array into the native order of the array indices in the file (model_times,5,48,40), then use transpose to reorder the indices to what you want (40,48,5,model_times). If you tried to reshape directly to the latter, you'd get data in the wrong places.

这篇关于MATLAB to Python读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆