Clear Filters
Clear Filters

Can my program add code to itself?

4 views (last 30 days)
I'd like to add a sort of learning ability to my program where it recognizes new name inputs and adds them to my current list as a way of future proofing it. I would be adding an elseif statement at the same line every time (just after the initial if). My current idea as I'm assuming you can't write to a file while it is currently running in MATLAB is to set a value of 1 or 0 which will run another program afterward to write to the original if 1, or end if 0.
Is there a simpler way of writing to a specific line (in this case line 16) in a .m file?
Where can I find more information on how to go about this?
  2 Comments
Stephen23
Stephen23 on 14 Nov 2017
Edited: Stephen23 on 14 Nov 2017
In general data should not be stored in an Mfile. That is what .mat files are for.
Use a .mat file, then your task is trivial. Why make your life much more difficult than it needs to be?
Adam Hicks
Adam Hicks on 14 Nov 2017
Thanks for the advice, I should have thought of that and will remember it in the future. However, this list is currently only 4 names in a switch statement (changed from if). It's unlikely to ever be larger than 10 if it ever even grows at all so in this case I'll probably just keep it in the main m-file. It might be good practice to also write a version using a mat-file.

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 14 Nov 2017
You can use fgetl() and fprintf() to write text to the m-file, as long as MATLAB doesn't have the m-file locked, which I don't think it does. I also agree with Stephen about that not being a wise approach, especially when better approaches are available.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!