交换结构数组中字段的值
Swapping values of fields in a Structure array
我有一个结构数组:
s(1)=struct('field1', value, 'field2', value, 'field3', value)
s(2)=struct('field1', value, 'field2', value, 'field3', value)
等等
如何将 field1 的所有值与 field2 的所有值交换?
我试过这个代码
a=[s.field1];
[s.field1]=s.field2;
[s.field2]=a;
虽然我可以将 field2 的值放入 field1,但我无法将 field1 的值放入 field2。
您的方法差不多。最简单的修复方法是将 a
存储为元胞数组,而不是数值数组,以便利用 MATLAB 的列表扩展:
s(1)=struct('field1', 11, 'field2', 12, 'field3', 13);
s(2)=struct('field1', 21, 'field2', 22, 'field3', 23);
a = {s.field1};
[s.field1] = s.field2;
[s.field2] = a{:};
[s.field1; s.field2]
的来源:
ans =
11 21
12 22
收件人:
ans =
12 22
11 21
对于更通用的方法,您可以利用 struct2cell
and cell2struct
交换字段:
function s = testcode
s(1)=struct('field1', 11, 'field2', 12, 'field3', 13);
s(2)=struct('field1', 21, 'field2', 22, 'field3', 23);
s = swapfields(s, 'field1', 'field2');
end
function output = swapfields(s, a, b)
d = struct2cell(s);
n = fieldnames(s);
% Use logical indexing to rename the 'a' field to 'b' and vice-versa
maska = strcmp(n, a);
maskb = strcmp(n, b);
n(maska) = {b};
n(maskb) = {a};
% Rebuild our data structure with the new fieldnames
% orderfields sorts the fields in dictionary order, optional step
output = orderfields(cell2struct(d, n));
end
结果相同。
我有一个结构数组:
s(1)=struct('field1', value, 'field2', value, 'field3', value)
s(2)=struct('field1', value, 'field2', value, 'field3', value)
等等
如何将 field1 的所有值与 field2 的所有值交换?
我试过这个代码
a=[s.field1];
[s.field1]=s.field2;
[s.field2]=a;
虽然我可以将 field2 的值放入 field1,但我无法将 field1 的值放入 field2。
您的方法差不多。最简单的修复方法是将 a
存储为元胞数组,而不是数值数组,以便利用 MATLAB 的列表扩展:
s(1)=struct('field1', 11, 'field2', 12, 'field3', 13);
s(2)=struct('field1', 21, 'field2', 22, 'field3', 23);
a = {s.field1};
[s.field1] = s.field2;
[s.field2] = a{:};
[s.field1; s.field2]
的来源:
ans =
11 21
12 22
收件人:
ans =
12 22
11 21
对于更通用的方法,您可以利用 struct2cell
and cell2struct
交换字段:
function s = testcode
s(1)=struct('field1', 11, 'field2', 12, 'field3', 13);
s(2)=struct('field1', 21, 'field2', 22, 'field3', 23);
s = swapfields(s, 'field1', 'field2');
end
function output = swapfields(s, a, b)
d = struct2cell(s);
n = fieldnames(s);
% Use logical indexing to rename the 'a' field to 'b' and vice-versa
maska = strcmp(n, a);
maskb = strcmp(n, b);
n(maska) = {b};
n(maskb) = {a};
% Rebuild our data structure with the new fieldnames
% orderfields sorts the fields in dictionary order, optional step
output = orderfields(cell2struct(d, n));
end
结果相同。