Matlab: renaming workspace elements from command window?
The GUI of Matlab allows me to rename any element in the workspace by right-clicking on the element and selecting the 'rename' option. Is it possible to do this from the command w开发者_开发百科indow as well?
These are things you can easily test for yourself, and you should do so. That is the best way to learn, to discover.
Regardless, the answer is no, you cannot change a variable name in that way from the command window. The command window is mainly for keyboard input only.
Edit: The question was apparently about doing that change by a command in the command window, not to be done via a mouse. (Why not tell us that up front?)
There is no explicit command that does such a rename. However, nothing stops you from writing it yourself. For example...
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)
You can rename variables in the command window as follows:
%# create a variable
a = 3;
%# rename a to b
b = a;clear('a');
EDIT
If you want to rename your variable to another variable stored in a string, you can use ASSIGNIN
a = 3;
newVarName = 'b';
assignin('base',newVarName,a);
clear('a') %# in case you want to get rid of the variable a
精彩评论