Matlab:从命令窗口重命名工作区元素?

时间:2011-05-11 12:58:26

标签: matlab command rename

Matlab的GUI允许我通过右键单击元素并选择“重命名”选项来重命名工作区中的任何元素。是否可以从命令窗口执行此操作?

2 个答案:

答案 0 :(得分:3)

这些是你可以自己轻松测试的东西,你应该这样做。这是学习,发现的最佳方式。

无论如何,答案是否定的,您无法从命令窗口以这种方式更改变量名称。命令窗口主要用于键盘输入。

编辑:问题显然是在命令窗口中通过命令进行更改,而不是通过鼠标完成。 (为什么不预先告诉我们?)

没有明确的命令可以进行重命名。但是,没有什么可以阻止你自己写。例如......

function renamevar(oldname,newname)
% renames a variable in the base workspace
% usage: renamevar oldname newname
% usage: renamevar('oldname','newname')
%
% renamevar is written to be used as a command, renaming a single
% variable to have a designated new name
%
% arguments: (input)
%  oldname - character string - must be the name of an existing
%          variable in the base matlab workspace.
%
%  newname - character string - the new name of that variable
%
% Example:
% % change the name of a variable named "foo", into a new variable
% % with name "bahr". The original variable named "foo" will no
% % longer be in the matlab workspace.
%
% foo = 1:5;
% renamevar foo bahr

% test for errors
if nargin ~= 2
  error('RENAMEVAR:nargin','Exactly two arguments are required')
elseif ~ischar(oldname) || ~ischar(newname)
  error('RENAMEVAR:characterinput','Character input required - renamevar is a command')
end

teststr = ['exist(''',oldname,''',''var'')'];
result = evalin('base',teststr);
if result ~= 1
  error('RENAMEVAR:doesnotexist', ...
    ['A variable named ''',oldname,''' does not exist in the base workspace'])
end

% create the new variable
str = [newname,' = ',oldname,';'];
try
  evalin('base',str)
catch
  error('RENAMEVAR:renamefailed','The rename failed')
end

% clear the original variable
str = ['clear ',oldname];
evalin('base',str)

答案 1 :(得分:2)

您可以在命令窗口中重命名变量,如下所示:

%# create a variable
a = 3;

%# rename a to b
b = a;clear('a');

修改

如果要将变量重命名为存储在字符串中的另一个变量,可以使用ASSIGNIN

a = 3;
newVarName = 'b';
assignin('base',newVarName,a);
clear('a') %# in case you want to get rid of the variable a