MATLAB: Automatically writing a function does not update until manually opening said function


For an application we are writing, we want the user to be able to write a controller for a certain experiment.
They can do this in an area that is indicated by 'UserbuildControllerTextArea' in the app. The controller is then put into a seperate file called 'PID_user_build.m', which is created in the following code:
function_gen = fopen('PID_user_build.m','w');
format_gen = 'function u_c = PID_user_controller(P,I,D,r,v_c,integrator,derivator,dt) \n';
A = length(app.UserbuildControllerTextArea.Value);
area = string.empty(A,0);
for i = 1:A
area(i,1) = sprintf('%s',app.UserbuildControllerTextArea.Value{i});
function_area = fopen('PID_user_build.m','a');
fprintf(function_area,'%s \n',area);
function_end = fopen('PID_user_build.m','a');
format_end = 'end';
The function file is created perfectly, it makes the file as desired with the controller neatly in the function.
The problem is that even though the file is created and saved, it is not 'updated' until the file is opened once:
A different function in the app tries to use this function, but if a new controller is saved by the script above, the app uses the old version of the controller until the file of the controller is opened (not even saved) once. It then runs the controller-function as desired.
We would like to remove this need for the file to be opened for the app to use the updated controller. Would any of you know what the problem is or how to fix it?
Thanks in advance!

Best Answer

  • You forgot the fclose statements.
    In addition you do not need to open the file twice for appending. This should work:
    fid = fopen('PID_user_build.m', 'a');
    fprintf(fid, '%s \n',area);
    fprintf(fid, 'end\n');