How to execute functions in Live editor in MATLAB - matlab

I recently started using Live editor in MATLAB and I inserted a function inside it. But, apparently, I cannot execute that particular section of code where I type function. Even the section break disappears.
Is it that using function is not suitable for live editor?

Apparently the MATLAB parser did not join the 20th century until partway through 2016, and could not interpret function definitions in scripts (live or otherwise) until R2016b. In the web-based docs, there is a notice at Add Functions to Scripts, but it took me a while to find this out because the builtin docs in R2016a or earlier do not explicitly contain this information. It is implied by the tutorials that tell you to create a new file for each function (which to me, a python programmer, sounds more like strange advice than a restriction).
Trying to define a function in a live script gives confusing errors. For example, if you create a cell with this content:
function y = myfunc(x)
y = 2*x;
end
It will underline the keyword function with a popup error that reads:
Parse error at FUNCTION: usage might be invalid MATLAB syntax.
Might be? Whom shall I ask? Upon running the cell, it prints an error after the first line:
All functions in a script must be closed with an end.
I eventually made this discovery myself thanks to a helpful message if the first thing you happen to do in a new empty live script is to start typing function on the first line; as soon as you hit the spacebar a message pops up at the top saying:
Functions and classes are not supported in the Live Editor. To continue, save the file as a plain text code file (.m).

It should work as when you add a function inside a script. For example, like this:
What function are you exactly trying to code?

Related

How Can I Run a Nonlinear Regression Macro in Minitab (simple syntax error)?

I'm new to scripting Minitab 17 and have run into a snag that I can't find any documentation for, including an error message that brings up no hits on Google. All I want to do is generate macros that perform simple nonlinear regressions automatically, all of which execute just fine in the GUI or through Session Commmands. If I follow the directions on p. 10 of the Minitab Macros documentation and copy the commands I've successfully run from the
Project Manager/History folder, copy them into a .MAC file and surround them with GMACRO and ENDMACRO commands, I end up with the code below:
GMACRO
NLinear;
Response 'MyColumn1';
Continuous 'MyOtherColumn2';
Parameter "Theta1" 0.5;
Parameter "Theta2" 0.2;
Expectation Theta1 * ln (MyOtherColumn2 - Theta2 );
NoDefault;
TMethod;
TStarting;
TConstraints;
TEquation;
TParameters;
TSummary;
TPredictions.
ENDMACRO
The code between the MACRO statements runs OK from the GUI or as a Session Command. When I run the resulting macro file from the session prompt in Minitab, however, I invariably receive the following error: "Arguments not allowed in all global macro mode." I also receive syntax errors for every column that includes quote marks, even though that is standard session window syntax; I can eliminate these by substituting the column heading from my open worksheet, such as "C1", but can't get past the other error.
I'm obviously using some kind of incorrect syntax element(s) but can't pin them down - does anyone have any ideas? There are plenty of instructional materials on Minitab macros on the Web, but I haven't yet encountered any that deal with either this particular error or that delve much into how to execute ordinary Minitab tests of this kind. My goal is merely to write batch files that will do all my nonlinear regressions on off-hours etc. Thanks in advance.
Re-read pages 10-11 of http://support.minitab.com/en-us/minitab/18/macros-help/#page10.
The line after GMACRO should be the name of the macro, not a command.
Also, note that in a global macro the column names in 'single quotes' must exist in the active worksheet.
the better way to learn Minitab macro is to do the job by the menu and then to go to the SESSION WINDOW and to look at how Minitab uses the function.
Do your Nonlinear Regression with your data and then in the SESSION WINDOW (first icon of the Project Manager bar) you will see the code. After that it is more easy to do macro.
In this case I think about an issue I had sometimes: I don't know why but sometimes I had to switch the regional setting ('.' instead of ',' for numeric values) or to write ',' instead of ';' in the macro.
You can try this.

How to show code from a script in a publish?

I want to publish my assignment with matlab.
At the start of the program, I want to print the code of my scripts to show the teacher what my functions do.
How can I do this?
So far the best way I do this is by making a dummy call at the start without ending the function call with ";"
However I'd really like to just print the code at the start.
You can use the type command:
type fileName.m
This will print the code, similarly to creating a variable and not using a semicolon to see the value of that variable.
There are tools in MATLAB for publishing code. You could conceivably even write a report in MATLAB code and publish that! Take a look at publishing MATLAB code and the documentation of the function publish
If you are interested to print particular lines from a .m file, look into dbtype.
Illustration from Mathworks site linked above. This:
becomes this:

Elusive MATLAB built-in function

I am trying to read the following internal MATLAB function:
>>which visionInitializeAndExpandCheckerboard
built-in (C:\Program Files\MATLAB\R2015a\toolbox\vision\vision\visionInitializeAndExpandCheckerboard)
But it appears to be hidden away! And very well hidden.
None of the following methods to access it have worked:
Highlighting the name and pressing Ctrl+D.
Typing "edit visionInitializeAndExpandCheckerboard" in the command line.
Searching for the file in Matlab's own FindFiles.
Searching for the file on the disk.
Trying to Step Into the function in debug mode (I just get the output as if I had requested Step Out instead).
Btw, the reason I am looking into this is that the parent function detectCheckerboardPoints has seriously declined in performance from R2015a to R2016b and I am trying to figure out why.
The internal function is compiled native code, so you will not be able to see its source. If you see a performance degradation, you should call Mathworks tech support and complain. If it is something they can fix, they will send you a patch, and fix it in the next release.

Can the MATLAB editor show the file from which text is displayed? [duplicate]

In MATLAB, how do you tell where in the code a variable is getting output?
I have about 10K lines of MATLAB code with about 4 people working on it. Somewhere, someone has dumped a variable in a MATLAB script in the typical way:
foo
Unfortunately, I do not know what variable is getting output. And the output is cluttering out other more important outputs.
Any ideas?
p.s. Anyone ever try overwriting Standard.out? Since MATLAB and Java integration is so tight, would that work? A trick I've used in Java when faced with this problem is to replace Standard.out with my own version.
Ooh, I hate this too. I wish Matlab had a "dbstop if display" to stop on exactly this.
The mlint traversal from weiyin is a good idea. Mlint can't see dynamic code, though, such as arguments to eval() or string-valued figure handle callbacks. I've run in to output like this in callbacks like this, where update_table() returns something in some conditions.
uicontrol('Style','pushbutton', 'Callback','update_table')
You can "duck-punch" a method in to built-in types to give you a hook for dbstop. In a directory on your Matlab path, create a new directory named "#double", and make a #double/display.m file like this.
function display(varargin)
builtin('display', varargin{:});
Then you can do
dbstop in double/display at 2
and run your code. Now you'll be dropped in to the debugger whenever display is implicitly called by the omitted semicolon, including from dynamic code. Doing it for #double seems to cover char and cells as well. If it's a different type being displayed, you may have to experiment.
You could probably override the built-in disp() the same way. I think this would be analagous to a custom replacement for Java's System.out stream.
Needless to say, adding methods to built-in types is nonstandard, unsupported, very error-prone, and something to be very wary of outside a debugging session.
This is a typical pattern that mLint will help you find:
So, look on the right hand side of the editor for the orange lines. This will help you find not only this optimization, but many, many more. Notice also that your variable name is highlighted.
If you have a line such as:
foo = 2
and there is no ";" on the end, then the output will be dumped to the screen with the variable name appearing first:
foo =
2
In this case, you should search the file for the string "foo =" and find the line missing a ";".
If you are seeing output with no variable name appearing, then the output is probably being dumped to the screen using either the DISP or FPRINTF function. Searching the file for "disp" or "fprintf" should help you find where the data is being displayed.
If you are seeing output with the variable name "ans" appearing, this is a case when a computation is being done, not being put in a variable, and is missing a ';' at the end of the line, such as:
size(foo)
In general, this is a bad practice for displaying what's going on in the code, since (as you have found out) it can be hard to find where these have been placed in a large piece of code. In this case, the easiest way to find the offending line is to use MLINT, as other answers have suggested.
I like the idea of "dbstop if display", however this is not a dbstop option that i know of.
If all else fails, there is still hope. Mlint is a good idea, but if there are many thousands of lines and many functions, then you may never find the offender. Worse, if this code has been sloppily written, there will be zillions of mlint flags that appear. How will you narrow it down?
A solution is to display your way there. I would overload the display function. Only temporarily, but this will work. If the output is being dumped to the command line as
ans =
stuff
or as
foo =
stuff
Then it has been written out with display. If it is coming out as just
stuff
then disp is the culprit. Why does it matter? Overload the offender. Create a new directory in some directory that is on top of your MATLAB search path, called #double (assuming that the output is a double variable. If it is character, then you will need an #char directory.) Do NOT put the #double directory itself on the MATLAB search path, just put it in some directory that is on your path.
Inside this directory, put a new m-file called disp.m or display.m, depending upon your determination of what has done the command line output. The contents of the m-file will be a call to the function builtin, which will allow you to then call the builtin version of disp or display on the input.
Now, set a debugging point inside the new function. Every time output is generated to the screen, this function will be called. If there are multiple events, you may need to use the debugger to allow processing to proceed until the offender has been trapped. Eventually, this process will trap the offensive line. Remember, you are in the debugger! Use the debugger to determine which function called disp, and where. You can step out of disp or display, or just look at the contents of dbstack to see what has happened.
When all is done and the problem repaired, delete this extra directory, and the disp/display function you put in it.
You could run mlint as a function and interpret the results.
>> I = mlint('filename','-struct');
>> isErrorMessage = arrayfun(#(S)strcmp(S.message,...
'Terminate statement with semicolon to suppress output (in functions).'),I);
>>I(isErrorMessage ).line
This will only find missing semicolons in that single file. So this would have to be run on a list of files (functions) that are called from some main function.
If you wanted to find calls to disp() or fprintf() you would need to read in the text of the file and use regular expresions to find the calls.
Note: If you are using a script instead of a function you will need to change the above message to read: 'Terminate statement with semicolon to suppress output (in scripts).'
Andrew Janke's overloading is a very useful tip
the only other thing is instead of using dbstop I find the following works better, for the simple reason that putting a stop in display.m will cause execution to pause, every time display.m is called, even if nothing is written.
This way, the stop will only be triggered when display is called to write a non null string, and you won't have to step through a potentially very large number of useless display calls
function display(varargin)
builtin('display', varargin{:});
if isempty(varargin{1})==0
keyboard
end
A foolproof way of locating such things is to iteratively step through the code in the debugger observing the output. This would proceed as follows:
Add a break point at the first line of the highest level script/function which produces the undesired output. Run the function/script.
step over the lines (not stepping in) until you see the undesired output.
When you find the line/function which produces the output, either fix it, if it's in this file, or open the subfunction/script which is producing the output. Remove the break point from the higher level function, and put a break point in the first line of the lower-level function. Repeat from step 1 until the line producing the output is located.
Although a pain, you will find the line relatively quickly this way unless you have huge functions/scripts, which is bad practice anyway. If the scripts are like this you could use a sort of partitioning approach to locate the line in the function in a similar manner. This would involve putting a break point at the start, then one half way though and noting which half of the function produces the output, then halving again and so on until the line is located.
I had this problem with much smaller code and it's a bugger, so even though the OP found their solution, I'll post a small cheat I learned.
1) In the Matlab command prompt, turn on 'more'.
more on
2) Resize the prompt-y/terminal-y part of the window to a mere line of text in height.
3) Run the code. It will stop wherever it needed to print, as there isn't the space to print it ( more is blocking on a [space] or [down] press ).
4) Press [ctrl]-[C] to kill your program at the spot where it couldn't print.
5) Return your prompt-y area to normal size. Starting at the top of trace, click on the clickable bits in the red text. These are your potential culprits. (Of course, you may need to have pressed [down], etc, to pass parts where the code was actually intended to print things.)
You'll need to traverse all your m-files (probably using a recursive function, or unix('find -type f -iname *.m') ). Call mlint on each filename:
r = mlint(filename);
r will be a (possibly empty) structure with a message field. Look for the message that starts with "Terminate statement with semicolon to suppress output".

How to interrupt MATLAB IDE when it hangs on displaying very large array?

Suppose I'm using the MATLAB IDE and happen to have some very large objects in my workspace (e.g. arrays of 500k+ elements). Now, suppose that I stupidly and accidentally double click on one of these very large variables, which triggers a load to the array editor. Unfortunately, with arrays this big, MATLAB just hangs.
I've tried CTRL+C, CTRL+BREAK, CTRL+D, but none seem able to interrupt the behavior of the IDE. I know I can force matlab to quit, but reading all of those variables into the workspace in the first place takes a lot of time, and I may have unsaved changes in an editor window, etc.
The variable editor is launched using the command openvar. To solve your problem you can take advantage of a Matlab quirk that causes functions to be masked by variables with the same name. For example if you create a variable named plot the plot() function stops working.
The solution, although hackish, is to simply create an empty variable named openvar. Then anytime attempt to open the variable editor will fail because the function openvar is being hidden by the variable.
If you want to use the variable editor again simple call clear openvar to delete the variable and the function will be unmasked.
I found a way, but it's not the best, it requires a change of path and back once to get a handle to the original openvar
function openvar(name,array)
persistent org_openvar
if isempty(org_openvar)
curdir=pwd;
cd(fullfile(matlabroot,'toolbox/matlab/codetools'));
org_openvar = #openvar;
cd(curdir);
end
if numel(array)>1e5
if strcmp(questdlg(sprintf('Opening ''%s'' which has %d elements.\n\nAre you sure? This is gonna take a while!',name,numel(array)), ...
'Variable editor','Yes','Cancel','Cancel') , 'Yes')
org_openvar(name,array)
end
else
org_openvar(name,array)
end
end
getting that handle is the biggest problem, calling it is just fine. If openvar would be built in, you could use the function builtin:
builtin('openvar',name,array)
but this is unfortunately not the case :(
str2func in combination with the complete path also doesn't work, at least I don't get it to work...