How can I extract only the comments in a code?
조회 수: 4 (최근 30일)
이전 댓글 표시
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
채택된 답변
Image Analyst
2016년 8월 17일
편집: Image Analyst
2016년 8월 17일
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
Image Analyst
2016년 8월 17일
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Environment and Settings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!