File Exchange

image thumbnail


version (2.36 KB) by Raymond Norris
Count lines of source code for an M-file


Updated 09 Mar 2006

View License

Counts the lines of source code in an M-file.

A line of source code is defined to be not a comment line, not a continuation of a previous line, and not an empty line.

The function line is included. SLOC returns the line count for the entire file, not for individual functions of a file.

If more than more statement is on the same line, that it treated as one line. For example, the line:

minx = 32; maxx = 100;

is one line of source code.

Cite As

Raymond Norris (2020). sloc (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (14)

Junshi Chen

very useful.


The comments state that sloc does not count the 'function' line, but it doesn't properly handle this if the fucntion line spans more than one physical line.
e.g.: function myfunc (arg1, ...
arg2, ...
arg3, ...

dm b



David Roberts

I created a function slocDir that uses this file to give sloc totals for each folder in a directory tree. Kind of confusing that there are two files out there slocdir & slocDir which seem to do the same thing. slocDir was submitted to Matlab Central a few weeks before slocdir.

Diffy D

I made a little script to list all the .m recursively and count the number of lines with sloc, you can fount it at :


Dionisio Arcano

Gregory Wunder

I have already developed a similar program. God Bless!

Jiro Doke

Good how you incorporated multi-line codes continued by <...>. But some commands can have multiple lines without <...>, such as mutli-row matrix definition. But I guess this will be hard to detect.

Andrej Mosat

I`d add:
line 32: file=deblank(file);
or similar, because:
returns a char array with spaces at the end.
error occurs: 'xyz.m .m' cannot be found
But spaces in the middle of file would need a regexp.

Andrej Mosat

Cool, I`d expect one more thing: to count all the lines for *.m files in the current directory recursively. Thanx, no rating yet.


Bug fixes:
(1) The MATLAB Profiler does not include the "function" line in it's metrics, so do not count the "function" line or any "function" lines for subfunctions. (2) Also, functions (particulary nested) may be indented, so minor fix for that.

Updated to support R14, specifically for block comments ( {%...}% )

MATLAB Release Compatibility
Created with R13
Compatible with any release
Platform Compatibility
Windows macOS Linux