Export data from C and read it in Matlab

For 1-D data

//  Write binary files using C
int buffer[6] = { 1,2,3,4,5,6 };
FILE* write_ptr;
write_ptr = fopen("test.kt", "wb");  
fwrite(buffer, sizeof(buffer), 1, write_ptr);
//  Read binary files using Matlab
clc;
[fid,mess] = fopen('test.kt','rb')
data = fread(fid,'int');

For 2-D data !!
The reshape in Matlab is by column instead of row (in C). So, we need to read it by column using the number of original row, and then transpose it.

    int buffer[2][3] = {
    
    1,2,3,4,5,6};
    FILE* write_ptr;
    write_ptr = fopen("test_w.zkt", "wb");  // w for write, b for binary
    fwrite(buffer, sizeof(buffer), 1, write_ptr); // write 10 bytes from our buffe
    fclose(write_ptr);
[fid,mess] = fopen('test_w.zkt','rb')
B =  fread(fid, 'int');
B =  reshape(B, [], 2).'

猜你喜欢

转载自blog.csdn.net/weixin_39987672/article/details/126116725
今日推荐