[英]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. 我有使用Matlab编码器导出到C ++代码的函数。 In the code a matrix is loaded from a mat file. 在代码中,矩阵是从mat文件加载的。 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: 我尝试了一种解决方案,首先使用fwrite
将文件另存为二进制文件,然后读取如下:
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. 但是,该函数以5Hz调用,因此在这种情况下会连续加载文件。 Is there a way to only load the file once in Matlab? 有没有一种方法只能在Matlab中加载一次文件? Or is there another approach to solve this problem? 还是有解决此问题的另一种方法?
PS: To pass the filename to the Matlab side I use in Matlab: PS:要将文件名传递到Matlab端,我在Matlab中使用:
coder.typeof('s',Inf);
and pass a variable of type emxArray_char_T
to the matlab function, create by: 并将类型为emxArray_char_T
的变量传递给matlab函数,创建方法如下:
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. 您可以在MATLAB中使用persistent
变量来仅在第一次调用函数时读取数据。 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. 我将fread
函数移到了c ++代码。 Although this is not really what I wanted to do. 尽管这不是我真正想做的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.