MATLAB error using "diary" - matlab

I'm learning MATLAB and for my homework am supposed to use the diary feature to save a file from the command window. I used the following code,
%% 2.21
clc
clear
diary( 'degrees.dat' )
columnOne = linspace(0, 180, 8);
columnTwo = columnOne .* (pi / 180);
D_to_R = [columnOne', columnTwo']
diary off
clc
clear
load ( 'degrees.dat' )`
and got the error:
Error using load
Number of columns on line 3 of ASCII file
degrees.dat must be the same as previous
lines.
I put the above code in the editor window but tried putting it directly in the command window and it didn't make a difference. The code up until loading the saved file seems to work fine and I can't see a difference in number of columns like the error indicates.
Any ideas?

You are using diary correctly. However, your use of load is incorrect, and most likely unneeded based on the problem at hand. You've shown that you can save a file with 'diary'.
If you want to show the contents of your diary as stored in the file degrees.dat in the command window you can type, into the command window:
type degrees.dat or type('degrees.dat').
Similarly, if you want to open it in the edit window you can use
edit('degrees.dat') or edit degrees.dat

Related

Programmatically save all dirty files in MatLab

Frequently I make the mistake of running my main.m when several files in the editor are dirty.
It would be nice if I could have a command at the start of my main.m that just automatically saves every dirty file.
Save currently running script in Matlab gives an answer with a clue for saving the currently active file, but is there a way to do this for ALL files?
You can use the com.mathworks.mlservices.MLEditorservice object to access the editor and save all dirty files.
service = com.mathworks.mlservices.MLEditorServices;
% Get a vector of all open editors
editors = service.getEditorApplication.getOpenEditors();
% For each editor, if it is dirty, save it
for k = 0:(editors.size - 1)
editor = editors.get(k);
if editor.isDirty()
editor.save();
end
end
Rather than blindly saving all files, you could modify this slightly so that you could pass a list of functions (your dependencies) and just save those.
function saveAll(varargin)
% Convert all filenames to their full file paths
filenames = cellfun(#which, varargin, 'uniformoutput', false);
service = com.mathworks.mlservices.MLEditorServices;
% Get a vector of all open editors
editors = service.getEditorApplication.getOpenEditors();
% For each editor, if it is dirty, save it
for k = 0:(editors.size - 1)
editor = editors.get(k);
% Check if the file in this editor is in our list of filenames
% and that it's dirty prior to saving it
if ismember(char(editor.getLongName()), filenames) && editor.isDirty()
editor.save();
end
end
end
And this could be called with multiple function names (as strings)
saveAll('myfunc', 'myotherfunc')

Find an unsuppressed line in a large script

I am running a script which is fairly large. In the output screen I get ans = 10.
The problem is that the code is very large and I cannot pin point where this output is coming from.
Are there any tips to find the origin of this output within the MATLAB environment since I prefer not to have a random output on the screen?
In the case of a single script file, you can programmatically invoke mlint to return all warnings in the form of a struct:
L = mlint('my_filename'); % No need for .m at the end
Inspecting the structure you could see the following:
This structure has a field named 'message' which contains various issues, among which is what we're after - 'Terminate statement with semicolon to suppress output (in functions).'. At this stage you can run
find( strcmp({L.message},... % output is not suppressed on purpose
'Terminate statement with semicolon to suppress output (in functions).') )
Then inspect the line numbers that get printed.
Alternatively, if you want to skip the variable editor, or want to inspect a whole folder of .m files, you can run mlintrpt (in the case of a folder) or mlintrpt('plotWithoutOutliers') (in the case of a single file) and get a report in the following form:
As Luis said: look for the mlint error. In code this is shown as an orange shaded = and orange wiggle beneath it; on the scroll bar on the right it shows an orange line which you can hover over to see what the warning is and click on to go to the warning.
Additionally I included the red errors for completion. These will cause your code to be unable to run. Same here, red wiggle + red line on the right.
Last, the square on the top right, by the arrow, will either be green (no problems), orange (warnings, but the code will be able to run usually) or red (code won't be able to run).
Used Dev-iL's answer to create a simple function that will tell you the lines of code that are not suppressed. This way you don't need to inspect the returned lines in the structure L. Example: lines = UnsuppressedLines('isEven.m')
function [lines] = UnsuppressedLines( matlabScript)
l = mlint(matlabScript);
unsuppressedInstances = find( strcmp({l.message},'Terminate statement with semicolon to suppress output (in functions).') )
if isempty(unsuppressedInstances)
fprintf('No unsuppressed lines in script')
lines = [];
else
lines = {l.line};
lines = lines(unsuppressedInstances);
end
end

MATLAB: uiopen AND get the name of that file?

I have a GUI that has pushbuttons. You push the button, it allows you to choose a file to open then loads that file into the workspace using uiopen('load'). This part works fine:
Then I would like it to return the name of the file it just opened, so that I can use it for telling the next part of the program which data to look at, and to get the name of the opened file to display in an edit box in the GUI itself. First issue more vital than second. Any help would be appreciated
thanks
Actually the function 'uigetfile' is usually used for openning standard dialog box for retrieving files, and the format is like:
filename = uigetfile
or
[FileName,PathName,FilterIndex] = uigetfile(FilterSpec)
This function, displays a modal dialogbox that lists files in the current folder and enables you to selector enter the name of a file. If the file name is valid and the fileexists, uigetfile returns the file name as astring when you click Open. Otherwise uigetfile displaysan appropriate error message, after which control returns to the dialogbox. You can then enter another file name or click Cancel.If you click Cancel or close thedialog window, uigetfile returns 0.
one example could be:
[FileName,PathName] = uigetfile('*.m','Select the MATLAB code file');
Also, you can use 'uigetdir' for doing the same for directories.
In addition, you can check this link: for matlab
You can use uigetfile to get the name of the file and open it using load(filename).

Programming of 'edit text' & 'pushbutton' components of a GUI in MATLAB's GUIDE tool

I have a .m file written with definition of input & output variables along with calling of other function files which calculate the numeric output from provided numeric input.
I want to build a GUI in MATLAB for the same.
What I require is coding information for
1)Retrieving numeric data from 'edit text' component & pass this data assigned as input data
2)Set an action by clicking push button to run the program, calculate output from input & display the numeric values as output.
As far as I understand your question, it's pretty easy. I hope this will be helpful.
1. open guide by typing guide in command window.
2. click blank gui
3. guide window will open
4. click and drag a push button and an edit text.
5. click the editor
6. save your file
7. go to the follwing function
function pushbutton_Callback(hObject, eventdata, handles)
and write down this code below.
str = inputdlg('Enter numbers (seperated by commas)');
num = str2num(str{1});
a=num(:,1);
b=num(:,2);
ans=a+b; //or whatever you want to do!
caption = sprintf('your answer is %.2f',ans)
set(handles.edit,'string',caption)

How do you retrieve the selected text in MATLAB?

MATLAB has several selection-sensitive capabilities. For example, if you select some text and press F9, it evaluates your selection. (Unless you've remapped your keyboard settings.)
I'd like to be able to replicate this functionality with for a shortcut. So, for example, I want to click a shortcut that displays the current selection. My shortcut callback would be disp(GetSelection()).
But what goes into GetSelection?
Thanks to #Yair Altman's undocumented Matlab, I was able to figure out the java commands to make this work.
Put this in a shortcut (or a function that is called by the shortcut):
%# find the text area in the command window
jDesktop = com.mathworks.mde.desk.MLDesktop.getInstance;
try
cmdWin = jDesktop.getClient('Command Window');
jTextArea = cmdWin.getComponent(0).getViewport.getComponent(0);
catch
commandwindow;
jTextArea = jDesktop.getMainFrame.getFocusOwner;
end
%# read the current selection
jTxt = jTextArea.getSelectedText;
%# turn into Matlab text
currentSelection = jTxt.toCharArray'; %'
%# display
disp(currentSelection)
I don't believe there is any way to control or read the selection from the Matlab text editor, there is no mention of such an API on the Mathworks website (at least from a quick search on Google). If you want this functionality to enable more advanced text editing, then you might want to consider setting the .m file editor to an external editor (http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_env/brxijcd.html). It may be possible to read the selection from a UIcontrol in a custom GUI, but I don't think this is what you want.
In case you want to use something like this but with text highlighted in the editor rather than in the command window.
I use the following code in order to be able to quickly check the nnz() of a variable, although you can change the code in the nested try-catch to whatever you need.
Lastly, I created a shortcut with this code in the top right of Matlab, which I access quickly by pressing Alt-1.
try
activeEditor = matlab.desktop.editor.getActive;
currentSelection = activeEditor.SelectedText;
try
eval(sprintf('val = nnz(%s);',currentSelection))
disp(sprintf('>> nnz(%s) = %s',currentSelection,num2str(val)))
catch ex
disp(ex.message)
end
catch ex
disp(ex.message)
end