How to use one matlab program to create a new .m file and insert executable code into it which is from a separate file?
조회 수: 2 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
Ameer Hamza
2018년 6월 24일
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
Ameer Hamza
2018년 6월 25일
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Performance and Memory에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!