简体   繁体   中英

How can I initialize variables at runtime using the matlab coder?

I have a function that I export with the matlab coder to C++ code. In the code a matrix is loaded from a mat file. I was using:

coder.load('filename.mat');

However this does not allow me to change the file at runtime.

I tried a solution by first saving the file as a binary using fwrite and then reading as follows:

fileId = fopen(filename_variable,'r');
file_data = fread(fileId,Inf,'double');
fclose(fileId);

This allows me to load different files at runtime. The function however is called at 5Hz and is thus continuously loading the file in this case. Is there a way to only load the file once in Matlab? Or is there another approach to solve this problem?

PS: To pass the filename to the Matlab side I use in Matlab:

coder.typeof('s',Inf);

and pass a variable of type emxArray_char_T to the matlab function, create by:

emxArray_char_T* filename = emxCreateWrapper_char_T(filename_char_pointer, 1, size);

You could use a persistent variable in MATLAB to just read the data on the first call to your function. This assumes that the data in the file would never change from call to call.

function y = foo(...)
persistent file_data;
if isempty(file_data)
    % This only runs on the first call to foo
    fileId = fopen(filename_variable,'r');
    file_data = fread(fileId,Inf,'double');
    fclose(fileId);
end
use(file_data);

I moved the fread function to the c++ code. Although this is not really what I wanted to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM