How to create a new m file automatically with filled in commands every time?
Show older comments
I wanted to have the ability of creating m files with some standard lines filled in like clear all; close all; datestr(now) every time I create a new file so that I do not have to enter them manually.
So I created a function mcreate(x) where x is the new m file I want to create. I have written the function like this.
function mcreate(x)
edit x
fid = fopen([x '.m'],'w');
fprintf(fid,'clear all;\nclose all;\n clc;\ndatestr(now);\n');fclose(fid);
a=[x '.m']
type a
delete x.m
Suppose now I invoke mcreate(ssrr)at the command prompt, it is creating a file called ssrr.m with the required lines. But it also is opening an editor window called x.m - which is unwanted. Also by type a wanted it to type ssrr.m but it is trying to type a that does not exist so it is giving an error to that effect.
I wanted to close the editor with x.m also too. how to close that window? Is there an opposite of 'open' command?
Thanks in advance.
Seetha Rama Raju Sanapala
Accepted Answer
More Answers (2)
Image Analyst
on 5 Dec 2014
I would just take the following code and paste it into a "shortcut" button on your tool ribbon so that it's always handy:
% Code to create a new file with default lines of code pre-entered into it.
% Get the name of the file that the user wants to save.
startingFolder = userpath
defaultFileName = fullfile(startingFolder, '*.m');
[baseFileName, folder] = uiputfile(defaultFileName, 'Specify a file');
if baseFileName == 0
% User clicked the Cancel button.
return;
end
fullFileName = fullfile(folder, baseFileName)
% Open a new file.
fileID = fopen(fullFileName, 'wt');
% Load it up with the lines of code you want in it.
fprintf(fileID, 'clc;\n');
fprintf(fileID, 'close all;\n');
fprintf(fileID, 'clear;\n');
fprintf(fileID, 'workspace;\n');
fprintf(fileID, 'format compact;\n');
fprintf(fileID, 'format long g;\n');
% Close the file.
fclose(fileID);
% Open the file in the editor.
edit(fullFileName);
This is much, much more convenient that having to remember and type some m-file name and pass it some function/file name.
1 Comment
goc3
on 16 May 2025
This answer was very helpful. Thanks.
What is the
a=[x '.m'] type a delete x.m
line of code trying to achieve?
I do something similar to this to create a template unit test function which I then open for further editing, but I just finish my creation of the file with:
open( myCreatedFilename );
and it opens the created file in the editor.
I don't understand from your code or question though whether you want your created file opened or not. You don't need an 'edit' instruction to create the file so if you don't want it open in the editor then just don't call 'edit'.
Categories
Find more on Programming in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!