-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathchange_fieldnames.m
41 lines (36 loc) · 973 Bytes
/
change_fieldnames.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
function new_struct = change_fieldnames(old_struct, oldnames, newnames, ~) % ~ noerror
% 2017-07-09 Matlab2006+ Copyright (c) 2017, W J Whiten BSD License
if nargin == 4
noerror = true;
else
noerror = false;
end
% check and adjust inputs
if ~isstruct(old_struct)
error('changefields: First argument must be a struct')
end
if ischar(oldnames)
oldnames = {oldnames};
end
if ischar(newnames)
newnames = {newnames};
end
if length(oldnames) ~= length(newnames)
error('changefields: Number of names not equal');
end
% undo struct
names = fieldnames(old_struct);
names1 = names;
values = struct2cell(old_struct);
% change names
for i = 1:length(oldnames)
ind = find(strcmp(oldnames{i}, names));
if isempty(ind) && ~noerror
error(['changefields: Name ''', oldnames{i}, ''' not in struct']);
elseif ~isempty(ind)
names1{ind} = newnames{i};
end
end
% create new struct
new_struct = cell2struct(values, names1);
end