Anteino
Anteino

Reputation: 1136

How transfer an array of integers from C to Matlab

Is there a somewhat easy way to transfer an array of integers from a C program to matlab? I have found several guides online on how to do it between C++ and Matlab, but not for C to Matlab.

I have several arrays of 1180 floats that I produce with a program written in C. Now I want to visualize this data in Matlab. I could have the C program export the Matlab code necessary to create the arrays hard-coded, but this seems unnecesarily devious.

I could just use the C++ method and compile my C program with a C++ compiler but at this point I am just curious if it can also be done in C.

Matlab can import .mat files, but these files seem to be encrypted or in binary format.

Please don't give suggestions on how to visualize the data in C, I have to do it in Matlab. I have a piece of code in Matlab that is returning weird results and I wrote the equivalent code in C, now I want to see if there is a difference in results. This way I can debug my Matlab code, since the end result has to be handed in in Matlab code.

My C code so far. Also I made a mistake in my initial upload, I want to transfer an array of integers.

FILE *f = fopen("Ps.bin", "wb");
for(int n = 1; n < N + 1; n++)
{
    converter.asInt = Ps[n];
    for(int i = 0; i < 4; i++)
    {
        fwrite(&converter.asBytes[i], sizeof(char), 1, f);
    }
}
fclose(f);

This is what I tried in matlab, but none of it gives the proper result. In all cases matlab makes an array of doubles, which I definately don't want. It just generates an array with values that are one of these three: 0, 0.0000 and 4.925.

Ps = fread(fopen('Ps.bin'))
Ps = fread(fopen('Ps.bin'), 1180)
Ps = fread(fopen('Ps.bin'), 1180, 'uint32')
Ps = fread(fopen('Ps.bin'), 1180, '2 * uint16')

Upvotes: 0

Views: 237

Answers (1)

Thombou
Thombou

Reputation: 407

Write a binary file in C (using fwrite, look here). From matlab, you can read it using the procedure here (freadfunction)

Upvotes: 3

Related Questions