MATLAB Answers

How can I print line numbers when I use the PUBLISH command in MATLAB?

283 views (last 30 days)
I want line numbers printed next to each line of my function when I publish functions using the PUBLISH command.
I would like to see something like
 
001 function y = MyFunc(x)
002 y = x.^2;
003 end

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 30 Mar 2015
Use the dbtype function for this purpose:
>>doc dbtype
You can achieve the same thing using code such as the following:
 
function mypublish(filename)
% A Custom publish function that includes the line
% number for each line in the function
% Usage: mypublish('myfun.m')
function_options.format='html'
function_options.evalCode=false;
function_options.showCode=true;
copyfile(filename, 'mytemp.m')
fid1 = fopen(filename);
fid2 = fopen('mytemp.m', 'w');
i=1;
while 1
tline = fgetl(fid1);
if ~ischar(tline)
break;
end
if ~isempty(tline)
tline = [num2str(i),' ', tline];
fprintf(fid2,'%s',tline);
fprintf(fid2,'%s\n','');
i = i + 1;
end
end
fclose(fid1);
fclose(fid2);
publish(filename, function_options); % publish original function without line numbers
publish('mytemp',function_options); % publish temp function with line numbers
delete('mytemp.m'); % delete temp M -file
Note that the second approach would give you more flexibility if you wanted to display more than the line number.
 
  1 Comment
Remo
Remo on 22 Jul 2014
Thanks for the code. I can handle this function to generate the MATLAB code in a html file but when copy the code into a word document the format (style, code highlightning ...) gets lost. I there a way to solve this problem?

Sign in to comment.

More Answers (1)

Neuron
Neuron on 30 Mar 2015
Edited: Neuron on 30 Mar 2015
I use Matlab 7.0.1 (R14SP1), published October 2004, and it has a function that does exactly this...
>> help dbtype
DBTYPE List M-file with line numbers.

Products


Release

R2008a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by