当我使用 MATLAB 时,有时我觉得需要对一些变量进行评论。我想将这些评论保存在这些变量中。因此,当我必须在工作区中处理许多变量时,我忘记了其中一些变量的上下文,我可以阅读我在每个变量中添加的注释。所以我想评论变量并将评论保留在其中。
5 回答
虽然我认为最好(也是最简单)的方法是通过给变量提供描述性名称来使变量自记录,但实际上有一种方法可以让您使用 MATLAB 的面向对象方面来做您想做的事情. 具体来说,您可以创建一个新类,该类继承一个内置类,以便它具有描述变量的附加属性。
事实上,文档中有一个示例完全符合您的要求。它创建了一个新类ExtendDouble
,其行为与 double 类似,只是它DataString
附加了一个属性,用于描述变量中的数据。使用这个子类,您可以执行以下操作:
N = ExtendDouble(10,'The number of data points')
N =
The number of data points
10
并且N
可以像任何双精度值一样在表达式中使用。使用这个示例子类作为模板,您可以创建其他内置数字类的“注释”版本,但不允许子类化的那些(、、、和char
)cell
除外。struct
function_handle
当然,应该注意的是ExtendDouble
,我可以像这样定义我的变量,而不是像上面示例中那样使用类:
nDataPoints = 10;
这使得变量自我记录,尽管需要更多的输入。;)
解决此问题的一种便捷方法是拥有一个为您存储和显示评论的函数,即类似于下面的函数,如果您调用它时会弹出一个对话框comments('myVar')
以允许您输入新的(或读取/更新以前的)对变量(或函数,或同事)标记的注释myVar
。
请注意,在您的下一个 Matlab 会话中,这些注释将不可用。要做到这一点,您必须添加保存/加载功能comments
(即每次更改任何内容时,您写入文件,并且任何时候启动该功能并且database
为空时,如果可能,您加载文件)。
function comments(name)
%COMMENTS stores comments for a matlab session
%
% comments(name) adds or updates a comment stored with the label "name"
%
% comments prints all the current comments
%# database is a n-by-2 cell array with {label, comment}
persistent database
%# check input and decide what to do
if nargin < 1 || isempty(name)
printDatabase;
else
updateDatabase;
end
function printDatabase
%# prints the database
if isempty(database)
fprintf('no comments stored yet\n')
else
for i=1:size(database,1)
fprintf('%20s : %s\n',database{i,1},database{i,2});
end
end
end
function updateDatabase
%# updates the database
%# check whether there is already a comment
if size(database,1) > 0 && any(strcmp(name,database(:,1)))
idx = strcmp(name,database(:,1));
comment = database(idx,2);
else
idx = size(database,1)+1;
comment = {''};
end
%# ask for new/updated comment
comment = inputdlg(sprintf('please enter comment for %s',name),'add comment',...
5,comment);
if ~isempty(comment)
database{idx,1} = name;
database(idx,2) = comment;
end
end
end
为您的评论声明另一个变量怎么样?
例子:
\>> num = 5;
\>> numc = 'This is a number that contains 5';
\>> whos
...
这是我在 StackOverflow 上的第一篇文章。谢谢。
始终始终保持 Matlab 编辑器打开,其中包含记录您所做操作的脚本。即变量赋值和计算。
唯一的例外是您想要进行实验的非常短的会话。一旦你有了一些东西——将它添加到文件中(当你可以看到你的整个历史时,它也更容易剪切和粘贴)。
这样您就可以随时重新开始。只需clear all
重新运行脚本。您的工作区中永远不会有随机的临时对象。
最终,当你完成时,你也会有一些接近“可交付”的东西。
您是否考虑过使用结构(或单元,尽管结构需要额外的内存使用)?
'>> 数据集1.numerical=5;
'>> dataset1.comment='这是包含5的数据集';
dataset1 =
numerical: 5
comment: 'This is the dataset that contains 5'