Mp. Roe
Mp. Roe

Reputation: 23

How to read a C outputfile into Matlab

I created a matrix that is 500x500 in C which is about 1MB if anyone wants to see --> (http://www.megafileupload.com/8mad/test) . I need to read it into Matlab so that I can visualise it with imagesc . It's supposed to be some math generated artwork and I am very curious to see what it looks like.

So far i tried this:

fid = fopen('test', 'r')
mydata = fread(fid, 'double')

but it doesn't really work.

On the other hand, If anyone could suggest a different way to write the file such that it's more Matlab friendly is much appreciated.

My file basically contains a matrix with 500x500 elements of integer type.

This is how i save it on C:

if(fwrite(img, sizeof(int), w*h, fp) != w*h)
    printf("File write error.");
    fclose(fp);

Upvotes: 0

Views: 33

Answers (2)

Rotem
Rotem

Reputation: 32084

Check the following:

  1. Open file Test for reading.
  2. Read 500x500 elements of type int32 into matrix I.
  3. Close the file.
  4. Transpose matrix I - because 2D arrays of C are row major, and MATLAB matrices are column major, you need to transpose a matrix written within C and read in MATLAB.
  5. Display the image using imagesc.

f = fopen('Test', 'r');
I = fread(f, [500, 500], 'int32');
fclose(f);
I = I';
imagesc(I);

enter image description here

Upvotes: 1

Jean-François Fabre
Jean-François Fabre

Reputation: 140148

you're creating a binary file containing integers. I assume those are 32 bit integers (you'd have to check that from the C side or use stdint.h and the int32_t type).

If you have 32 bit integers stored, you could read your matlab file just like you're doing but using the correct type:

mydata = fread(fid, 'int32')

else matlab will map your integer values 2 by 2 into doubles and you'll probably get 0 or NaN values.

Then you get a 1D array, to reshape your array into a 2D array, have a look at the reshape function. Check this answer for instance.

Upvotes: 0

Related Questions