python读取matlab_MATLAB to Python读取

本文讨论了从MATLAB代码转换到Python过程中遇到的问题,特别是如何使用Python等效于MATLAB的fread函数来处理多维数组的读取,并提供了一个有效的解决方案。

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

The MATLAB code:

for time = 100:model_times

for i = 1:5

indat = fread(fid,[48,40],'real*4');

vort(:,:,i,time) = indat';

end

end

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).

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).

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)

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."

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

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()

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.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值