How to use one matlab program to create a new .m file and insert executable code into it which is from a separate file?

3 vues (au cours des 30 derniers jours)
Hello, I am attempting to create a function which determines variable values at different points in various separate programs which have certain variable values change. My program currently creates cell arrays of all code that is run in the program prior to each 'point'; these cell arrays look like this:
{0×0 char }
{'structure.A = 2; % Details' }
{'structure.B = 3; % Details' }
{'structure.C = 4; % Details' }
How would I go about copying this cell array into a new program and then running the program? This is what I have so far:
TempFileDirectory = [pwd,'\TempFile.m'];
FID = fopen(TempFileDirectory,'w');
fprintf(FID, '%s', char(FullText(1:65,:)));
fclose(FID);
TempFile;
This, however, does not work properly; instead of copying the code over into the new temporary file just as it is in the original file, it merges all of the code into one line which (obviously) cannot be executed. What do I do to fix this?
Thanks

Réponse acceptée

Ameer Hamza
Ameer Hamza le 24 Juin 2018
I don't understand why you need to create files dynamically like this. I believe there must be some other ways to do this task efficiently. Regardless, it appears that you are using the fprintf() incorrectly. You also didn't mention the content of FullText variable. Look at the following example to get some idea about how can you create such a script file dynamically
x = {'a=1;'; 'b=2;'; 'c=3;'};
f = fopen('tmpfile.m', 'w');
fprintf(f, '%s\n', x{:});
fclose(f);
tmpfile;
As a side note, instead of creating file path by concatenation, as you are doing in TempFileDirectory, it is better to use fullfile() to join paths.
  3 commentaires
Ameer Hamza
Ameer Hamza le 25 Juin 2018
In your question, you already mentioned that you have a cell of code like this
{0×0 char }
{'structure.A = 2; % Details' }
{'structure.B = 3; % Details' }
{'structure.C = 4; % Details'
So I suppose that you already have a cell array containing all the code, and the only problem you are facing is that, the fprintf() command is pasting this cell array into one line in a new .m file. In the code I gave, you can use any cell array in place of x (not just limited to 3 elements). The code will create a separate line for each element of the cell array.
Ak K
Ak K le 25 Juin 2018
Ok, I see. My apologies, that makes a lot of sense. Thank you for your answer.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Variables dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by