How can I extract only the comments in a code?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
JasMar
am 17 Aug. 2016
Kommentiert: Image Analyst
am 17 Aug. 2016
I am trying to extract only the comments from a code that has comments embedded in it?
I have experimented with the publishing features, but have not found a way to pull out only the comments from my code.
Thank you
0 Kommentare
Akzeptierte Antwort
Image Analyst
am 17 Aug. 2016
Bearbeitet: Image Analyst
am 17 Aug. 2016
Try this:
% Extracts all comments from a file. Prints to command window and stores in a cell array.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
% Have user browse for a file, from a specified "starting folder."
% For convenience in browsing, set a starting folder from which to browse.
startingFolder = pwd;
if ~exist(startingFolder, 'dir')
% If that folder doesn't exist, just start in the current folder.
startingFolder = pwd;
end
% Get the name of the file that the user wants to use.
defaultFileName = fullfile(startingFolder, '*.*');
[baseFileName, folder] = uigetfile(defaultFileName, 'Select an m file');
if baseFileName == 0
% User clicked the Cancel button.
return;
end
fullFileName = fullfile(folder, baseFileName)
fid = fopen(fullFileName, 'rt');
textLine = fgetl(fid);
ca = cell(1);
while ischar(textLine)
textLine = fgetl(fid);
percentLocation = strfind(textLine, '%');
if ~isempty(percentLocation)
% Print to command window
fprintf('%s\n', textLine(percentLocation:end));
% Save to a cell array
ca{end+1} = textLine;
end
end
% Close the file
fclose(fid);
% Get rid of empty first cell left over from initialization.
ca = ca(2:end);
% Display cell array in command window.
fprintf('\n========================================================\nHere is the cell array:\n');
celldisp(ca);
It could be simpler if you took out the part where you browse for the filename, and if I knew how you wanted your output (what form it is supposed to be in), but I made it as general and flexible as practical.
3 Kommentare
Image Analyst
am 17 Aug. 2016
I don't know what you mean by formatting. If you mean the automatic line wrap, then so. There's no way, short of reading and interpreting it to know if a comment below a line with a comment is a continuation of that comment, or an entirely separate and unrelated comment.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Environment and Settings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!