What do end-of-line commas do in Matlab? - matlab

This is hard to look up: what do the end-of-line commas do in Matlab? In the couple of small tests I've done, they don't seem to make the code behave any different. I'd like to know because they're all over in this code I didn't write (but have to maintain).
Examples of what I mean:
if nargin<1,
% code
end
if isError,
% code
end
try,
% code
while 1,
% even more code
end
catch,
% code
end

According to the documentation for the comma character in MATLAB, one of its functions is to separate statements within a line. If there is only one statement on a line, the comma is not needed. I don't like to see it there, although I know some people write code that way.

As others have pointed out, commas at the end of a line are unnecessary. They are really just for separating statements that are on the same line. mlint and the Editor will even give you a warning if you use one without needing it:
>> mlint comma_test.m
L 1 (C 4): Extra comma is unnecessary.

If you read tightly coded m-files (e.g., many of the built-in MATLAB functions) you will discover a variant of the if ... end construct that is written on one line. Here's an example
if x<0, disp('imaginary'); end
Notice the comma between the x<0 and the disp(...). Apparently the comma tells the MATLAB interpretter that the conditional test has ended. To my knowledge this is only place where a statement (OK, part of a statement) ends with a comma. It's just one of those quirks that true believers come to use without hesitation.
http://web.cecs.pdx.edu/~gerry/MATLAB/programming/basics.html

I think the comma in matlab is like the semicolon in C. It separates commands, so you can put multiple commands in one line separated by commas.
The way your program is written, I believe the commas make no difference.

Related

When to use % or %variable% in AutoHotKey?

I have searched around quite a bit and have failed to find an answer. In AutoHotKey, I am not sure the difference when a single percent is used near the beginning of a line, and when a variable is enclosed between two percent signs. I usually use trial and error to find when I use one or the other, I am hoping someone could shed some light on what the difference is or explain what it is actually doing.
Here are some examples of this in action.
Example 1: I noticed if you have multiple variables along with text, scripts tend to go with the preceding percent. Such as:
some_val := Clipboard
loop 5
msgbox % "Index:" . A_Index . ", variable:" . some_val
Example 2: I often see this as well, and sometimes it appears it must be used. Is this true?
some_variable := "test text to send"
Send, %some_variable%
Wrapping in double percent signs is legacy AHK and basically there is no need to ever use it anymore. Only reason to wrap in double % would be being stuck behind in the old times, or maybe one could argue it also being more convenient, or something, to write in some cases, but I'm not buying it.
The legacy syntax is replaced by expression syntax.
The expression syntax is closer to how many other languages behave. AHK legacy syntax really is a mess.
All legacy commands (MsgBox for example) use the old legacy syntax on each parameter (unless otherwise specified).
If you specify a % followed up by a space at the start of the parameter, you're forcing AHK to evaluate an expression on that parameter instead of reading it as a legacy text parameter.
Example:
MsgBox, 5+5
We're using a legacy command, we're not starting the parameter off with a % and a space, so we're using the legacy syntax. The MsgBox is going to print the literal text 5+5 instead of 10.
MsgBox, % 5+5
Again, legacy command, but now we're forcing AHK to evaluate an expression here, 5+5.
The result of expression's evaluation is going to be passed onto the MsgBox command and the MsgBox is going to print 10.
If we wanted to MsgBox to print the literal text 5+5, and use the expression syntax to do it, we'd do MsgBox, % "5+5".
Quotation marks in expression syntax mean we're specifying a string.
Well then there's the problem of knowing when you're in expression syntax, and when you're in the legacy syntax.
By default, you're basically always in an expression.
You leave it by for example using a command or = to assign.
If the difference between a command and a function isn't clear to you, here's an example:
Command, % 7+3, % MyCoolArray[4], % SomeOtherNiceFunction(), % false
Function(7+3, MyCoolArray[4], SomeOtherNiceFunction(), false)
In the command we specified a % followed up by a space to evaluate the expressions on each parameter, and in the function, we didn't have to do that since we're already in an expression.
And if you're not clear on the difference between = and :=,
= is legacy and deprecated, it assigns plain text to a variable
:= assigns the result of an expression to a variable.
So that's what I could write from on top of my head.
If you had some more complex examples, I could try showing on them. Maybe convert some code you may have over to expression syntax, make it 100% free of legacy syntax.
And here's a good page on the documentation you should give a read:
https://www.autohotkey.com/docs/Language.htm

Using fprintf() and disp() functions to display messages to command window in MATLAB?

Currently working on a project in which I must take multiple user-inputs. Because my input prompts must outline specific formatting to the user regarding how they should input their values, this makes each input prompt rather lengthy and so I've deemed it appropriate to separate each one with a line break so that it's easy to tell them apart/so that it looks nice. The last prompt is two lines long, so it would be hard to distinguish this one from the rest if they were all jumbled together rather than separated by line breaks.
I've explored the usage of fprintf() and disp(), and have found that fprintf() has some tricky behavior and sometimes will not work without including things like fflushf(), etc. Moreover, I've read that fprintf() is actually purposed for writing data to text files (from the MathWorks page, at least), and using it for another purpose is something I could definitely see my professor deducting points for if there is indeed an easier way (we are graded very harshly on script efficiency).
The disp() command seems to be more in-line with what I'm looking for, however I can't find anything on it being able to support formatting operators like \n. For now, I've resorted to replacing the usage of \n with disp(' '), however this is certainly going to result in a deduction of points.
TL;DR Is there a more efficient way to create line-breaks without using fprintf('text\n')? I'll attach a portion of my script for you to look at:
disp('i) For the following, assume Cart 1 is on the left and Cart 3 is on the right.');
disp('ii) Assume positive velocities move to the right, while negative velocities move to the left.');
prompt = '\nEnter an array of three cart masses (kg) in the form ''[M1 M2 M3]'': ';
m = input(prompt);
prompt = '\nEnter an array of three initial cart velocities (m/s) in the form ''[V1 V2 V3]'': ';
v0 = input(prompt);
disp(' ');
disp('Because the initial position of the three carts is not specified,');
prompt = 'please provide which two carts will collide first in the form ''[CartA CartB]'': ';
col_0 = input(prompt);
You can get disp to display a new line with the newline function. Putting multiple strings in square bracket will concatenate them.
disp(['Line 1' newline 'Line 2'])
You mention using fprintf, but as you found this is meant for writing to files. You can use the sprintf function to display the same formatted strings if desired.
disp(sprintf('Line 1 \nLine 2'))
In addition to Matt's solution, I figured out another way to solve my problem and wanted to post it here for anyone in the future with the same problem.
After some experimentation and some thought, I figured the most efficient way to do this (ideally) would not involve using disp() or fprintf() at all and instead would, in theory, involve actually manipulating the input prompts themselves to appear on multiple lines (rather than adding 'dummy' lines before the last line of each prompt, to make it seem as if it was all part of the prompt itself). I've been aware this whole time that simply a newline character \n will give me a linebreak in the middle of the sentence, and in theory this would work. But because the very last prompt is two lines long, simply typing one line with \n halfway through would make that line of code very long, which is what I was trying to avoid in the first place.
I realize my initial question didn't explicitly mention concatenating two (or more) strings to form an input prompt that appears on multiple lines both in the console and in the script itself, but that's essentially where I was going with this post and I apologize for any lack of clarity regarding this.
Anyways, I fixed this problem without having to use disp() or fprint() by declaring the prompt as a string array, rather than as a single string with the preceding lines of the prompt specified above it using disp() and/or fprintf() as you can see in the code I originally provided in the question. Here's how it looked before:
disp(' ');
disp('Because the initial position of the three carts is not specified,');
prompt = 'please provide which two carts will collide first in the form ''[CartA CartB]'': ';
col_0 = input(prompt);
versus how it looks now:
prompt = ['\nBecause the initial position of the three carts is not specified, please',...
'\nprovide which two carts will collide first in the form ''[CartA CartB]'': '];
col_0 = input(prompt);
In short, you can concatenate portions of the entire prompt by declaring it as a string array and inserting \n where you see fit.

q/kdb: How do I break my code into lines. Is there a new line 'escape' character or something similar?

I am writing long scripts on one line. I would like to organise my code by breaking code onto multiple lines without having to write a function. How do I do this?
You can separate code over multiple lines as long as you indent each subsequent line. You should use semi colons to separate expressions which are indented.
For example a simple select statement split over multiple lines could look like this;
t:([]a:1 2 3;b:`a`b`c);
res:select
from t
where a<>1,
b in `a`c;
show res
More information can be found here;
http://code.kx.com/q/tutorials/startingq/language/#29-scripts

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".

File reading in matlab

I'm having troubles with my code in Matlab. I want to get the mean value of all the elements in the second column in a file, but for some reason the code does not include the last line.
My file looks like this:
And my code looks like this:
As you might already understand, my code gets the mean value of all numbers except the last one for Italy.
Any suggestions on how to proceed would be highly appreciated.
It's actually suggested by Mathworks to not use feof with fgetl loops, but to instead check whether the output is with ischar. Simply replace ~feof(fid) with ischar(line).
A side note: line is also a MATLAB function, by using it as a variable name you are shadowing the function. While it is not critical here, you should try to avoid doing this. If you try to use line the function or another function which calls line while you have a variable line in the workspace, you'll likely get an error. This is why you'll see the examples in the help use things like tline as variable names instead.
You should put
line=fgetl(fid)
to the top in the while loop.