Can we use a command to append any text to the current edited file or after prompt - matlab

1) suppose I use the 'edit' command only an unnamed file 'untitled'.
can I use any command to append any text to the file 'untitled'?
2) Is there a command that can write a command after the prompt symbol >> w/o pressing enter. Like
>> doit
This is different from printf. printf('doit') does the following
doit
>>

To add text in a file 'untitled.m' using a function doit()
function doit()
fid = fopen('untitled.m','w'); % open file with write access
fprintf(fid,'%s','This text will appear in untitled.m'); % write some text as string (%s)
fclose(fid); % close the file (important!)

Related

Shortcut for saving file in current directory with correct name?

Is there any shortcut for saving an open file into the current directory with the current name? If I download multiple files with the same name they go into my Downloads folder and they end up with names like function (1).m instead of function.m.
At this point it's easy to open the file and see the contents by opening the file from my web browser- MATLAB sees the file extension and opens it. However, if it's a function, I have to Save As and move/rename the file before I'm able to use the code.
Edit: Since MATLAB insists that the file name be the same as the function name I'm hoping that there's a shortcut that saves an open file directly to the current MATLAB path and names it appropriately.
Since MATLAB convention is that the file name is the same as the function name I'm hoping that there's a shortcut that saves an open file directly to the current MATLAB path and names it according to the function name specified in the file.
You will need a directory which is always on the Matlab path. This can be achieved by adding one in the startup.m script.
Then you should save the below function savefunc.m to that directory, so you can always call it.
function savefunc(FuncName, Directory)
% Set directory if not given, default is working directory
if nargin < 2; Directory = pwd; end
% Get active document
ActiveDoc = matlab.desktop.editor.getActive;
% Set FuncName if not given, or if FuncName was empty string
if nargin < 1 || strcmp(FuncName, '');
% Get function name
FuncName = ActiveDoc.Text; % Entire text of document
% Could use indexing to only take first n characters,
% and not load entire string of long function into variable.
% FuncName = ActiveDoc.Text(1:min(numel(ActiveDoc.Text), n));
FuncName = strsplit(FuncName, '('); % Split on parenthesis
FuncName = FuncName{1}; % First item is "function [a,b,c] = myFunc"
FuncName = strsplit(FuncName, ' '); % Split on space (functions don't always have equals)
FuncName = strtrim(FuncName{end}); % Last item (without whitespace) is "myFunc"
end
% Save the file
saveAs(ActiveDoc, fullfile(Directory, [FuncName, '.m']));
end
Now, say you have just created the following Untitled.m:
function [a,b,c] = mytest()
a = 1; b = 1; c = 1;
end
The shortcut: just have Untitled.m open, and type into the Command Window
savefunc()
Untitled.m will be saved as mytest.m in the current working directory. Notice you can also pass a different function name and save-as directory if you wish, making this useful for other occasions.
You can pass an empty string as the FuncName if you want to specify the directory but use the auto-naming.
You could extend this using matlab.desktop.editor.getAll to get all open documents, then loop through them for saving.
For more info, type help matlab.desktop.editor in the Command Window, online documentation seems lacking.
matlab.desktop.editor: Programmatically access the MATLAB Editor to open, change, save, or close
documents.
Finally, note there is no need for a "Save successful" type message, since you will see the file name change, and also receive an error if it fails (from the saveAs docs):
If any error occurs during the saveAs operation, MATLAB throws a MATLAB:Editor:Document:SaveAsFailed exception. If the operation returns without an exception being thrown, assume that the operation succeeded.

Why does fprintf command display >> in MATLAB?

Here is a sample of a random script in MATLAB.
prompt = 'Please enter a lowercase x: ';
str = input(prompt, 's');
if str == 'x'
else
fprintf('Error, you did not enter a lowercase x.')
end
This always display what I have in the fprintf command with a >> at the end of it in the command window. For example, in this random context it would display ...
Error, you did not enter a lowercase x.>>
Simple question, yet I'm new to MATLAB. Why do I get a >> at the end of every fprintf command? Can't seem to figure it out.
You did not specify a line-break in your string, so fprintf pushes the text to the command windows and spawns another input prompt (the >>) directly after the text. Add a line break meta-character to the string (\n) to fix the issue:
fprintf('Error, you did not enter a lowercase x.\n')
Also, if your goal is to issue an error, you should use the error function. It halts execution of the code and colors the message red like other MATLAB errors.
Here the fprintf simply displays the text and returns to command console.
Use newline '\n' character,
fprintf('Error, you did not enter a lowercase x.\n');
% ~~~
to come back atfer newline with >> prompt

Call a function of a file .m in matlab

I have a file .m and I want call a function of file .m.
For example, I have the file MdeD.m:
function ESC = EDLECE(HOJA,POSF,POSC)
fid = fopen(HOJA,'r','n','UTF-8');
for i=1:POSF
tline = fgetl(fid);
end
COL = '%s';
for i=2:POSC-1
COL = strcat(COL, ' %s');
end
ESC = textscan(tline,strcat(COL,' %d'));
ESC = ESC{1,POSC};
end
and I want call the function EDLECE in another file .m. How do I do it?
(I sorry for my english)
Save the function in a file with the same name as the function and the .m file extension. In this case, it would be EDLECE.m. Put the file in the current working directory or in any directory in your search path.
From the other .m file, just call the function by it's name, like this:
ESC = EDLECE(HOJA,POSF,POSC);
Click here for instructions on how to view/modify your search path.
It depends whether the file MdeD.m contains only the function EDLECE or whether EDLECE.m is a subfunction in MdeD.m.
If MdeD.m only contains the EDLECE function, then you should really name the file EDLECE.m and you should be able to use the function just like any Matlab function as long as EDLECE.m is in your search path.
On the other hand, if EDLECE is a subfunction in MdeD.m, then you can't use it from another function/script or the command window. You will have to pull it out of MdeD and save it as its own function.

how to create a command alias in Matlab

Is there a similar concept to Unix 'alias' within Matlab?
This question Is there a way to do command aliasing in matlab R2011b? suggests defining anonymous functions, and extending the answer these could be sourced at startup, but this results in the function handles appearing in the Workspace, which will disappear when cleared.
Is there a more robust and Unix analogous solution? Seems like a pretty useful thing to be able to do...
I am not sure why you would want to do this, but...
Assuming you are willing to have a directory on the path dedicated to aliases you can create m files in that directory to run the aliases. In this case the aliases will not exist in the workspace. You could of course just write the alias files your self, but the following function will create aliases for you automatically. The function can get confused if the function/script you are trying to alias is not currently on the search path. The function is not "perfect" in the sense that you do not write
alias myAlias = run('full/path/to/some/script')
but rather
alias myAlias full/path/to/some/script
function alias(aliasName, functionName)
% alias myfoo foo
aliasPath = './alias';
isscript = false;
try
nargin(functionName);
catch %#ok<CTCH>
isscript = true;
end
if isscript
fileID = fopen([aliasPath, aliasName, '.m'],'w');
fprintf(fileID, '%s\n', ['run(', functionName, ')']);
fclose(fileID);
else
fileID = fopen([aliasPath, aliasName, '.m'],'w');
fprintf(fileID, '%s\n', ['function varargout = ', aliasName, '(varargin)']);
fprintf(fileID, '\t%s\n', ['varargout{1:nargout} = ', functionName, '(varargin{:});']);
fprintf(fileID, '%s\n', 'end');
fclose(fileID);
end
end
Yes there is a way. It's called a function. You just write a function to do whatever you want the alias to do. For example:
function cdhome
cd(getenv('MATLABUSERPATH'))
Then just type cdhome at the command line, exactly like an alias in a unix shell. Note that MATLABUSERPATH is an environment variable I define in startup.m. It can be easier, just save a script called cdhome.m with the following content:
cd(getenv(<ENVIRONMENT_VARIABLE_THAT_DEFINES_MY_FAVORITE_PATH>))
Or how about:
clc; clear; close all;
Save that in a script file called clean.m and then simply put clean at the top of your scripts instead of clc; clear; close all;
No, it doesn't exactly follow the unix idea of having a bunch of alias's in a single configuration file that executes on startup.
But you can do that too. Put all your aliases in a switch block, in one function, call it alias:
function alias(thecalledalias)
switch thecalledalias
case somealias
% ... define some alias
case someotheralias
% ... define some other alias
end
For autocomplete, which you would get with your shell, put a functionSignatures.json file in the same folder as the alias.m function file and populate it with your aliases:
{
"_schemaVersion": "1.0.0",
"alias":
{
"inputs":
[
{"name":"thecalledalias", "kind":"required",
"type":["char", "choices={'somealias','someotheralias'}"]}
]
}
}
Then you will get autocomplete when you type alias(...) at the command line.
But to me it is easier to have one folder, call it myaliases with one script or function for each alias, and you get autocomplete at the command line just like when you call any function (i.e., no need to type alias(<somealias>)).

MATLAB: How do you insert a line of text at the beginning of a file?

I have a file full of ascii data. How would I append a string to the first line of the file? I cannot find that sort of functionality using fopen (it seems to only append at the end and nothing else.)
The following is a pure MATLAB solution:
% write first line
dlmwrite('output.txt', 'string 1st line', 'delimiter', '')
% append rest of file
dlmwrite('output.txt', fileread('input.txt'), '-append', 'delimiter', '')
% overwrite on original file
movefile('output.txt', 'input.txt')
Option 1:
I would suggest calling some system commands from within MATLAB. One possibility on Windows is to write your new line of text to its own file and then use the DOS for command to concatenate the two files. Here's what the call would look like in MATLAB:
!for %f in ("file1.txt", "file2.txt") do type "%f" >> "new.txt"
I used the ! (bang) operator to invoke the command from within MATLAB. The command above sequentially pipes the contents of "file1.txt" and "file2.txt" to the file "new.txt". Keep in mind that you will probably have to end the first file with a new line character to get things to append correctly.
Another alternative to the above command would be:
!for %f in ("file2.txt") do type "%f" >> "file1.txt"
which appends the contents of "file2.txt" to "file1.txt", resulting in "file1.txt" containing the concatenated text instead of creating a new file.
If you have your file names in strings, you can create the command as a string and use the SYSTEM command instead of the ! operator. For example:
a = 'file1.txt';
b = 'file2.txt';
system(['for %f in ("' b '") do type "%f" >> "' a '"']);
Option 2:
One MATLAB only solution, in addition to Amro's, is:
dlmwrite('file.txt',['first line' 13 10 fileread('file.txt')],'delimiter','');
This uses FILEREAD to read the text file contents into a string, concatenates the new line you want to add (along with the ASCII codes for a carriage return and a line feed/new line), then overwrites the original file using DLMWRITE.
I get the feeling Option #1 might perform faster than this pure MATLAB solution for huge text files, but I don't know that for sure. ;)
How about using the frewind(fid) function to take the pointer to the beginning of the file?
I had a similar requirement and tried frewind() followed by the necessary fprintf() statement.
But, warning: It will overwrite on whichever is the 1st line. Since in my case, I was the one writing the file, I put a dummy data at the starting of the file and then at the end, let that be overwritten after the operations specified above.
BTW, even I am facing one problem with this solution, that, depending on the length(/size) of the dummy data and actual data, the program either leaves part of the dummy data on the same line, or bring my new data to the 2nd line..
Any tip in this regards is highly appreciated.