1

I generated code for loading a mat file as follows

data=coder.load('data.mat');
a=data.a;
b=data.b;

Because one of the variables, for example "a", is very big, it is defined as a big static const array in the main function with all values initialized there.

Is there any way I can make MATLAB Coder load data from a file in C Code instead of defining it as a variable in main function?

2 Answers 2

3

The MATLAB fread function is supported for code generation. So you can fwrite the data to a file in MATLAB and then fread it in the generated code. This will do a runtime read and avoid the giant constant in the generated code.

1
  • Try to specify the precision argument to fread and fwrite. Say you have int32 values, then use 'int32' to write and '*int32' to read them as 32-bit integers. Just change the type name for your example. Mar 5, 2019 at 0:02
1

This is the exact code that we should use based on Ryan's answer:

load('Data.mat')
fileID = fopen('Data.bin', 'w');
fwrite(fileID, Matrix1,'uint64');
fclose(fileID);


fileID=fopen('Data.bin');
Matrix2=fread(fileID,[256,256],'uint64');
fclose(fileID);

Matrix 2 is now the same as Matrix 1. The trick for writing and reading is to use the same precision based on the data type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.