Arrays 交换结构数组中字段的值
我有一个结构数组:Arrays 交换结构数组中字段的值,arrays,matlab,field,structure,Arrays,Matlab,Field,Structure,我有一个结构数组: 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,但无
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。你的方法基本上达到了目的。最简单的修复方法是将
存储为单元格数组,而不是数字数组,以便利用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
致:
对于更一般的方法,您可以利用和交换字段:
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
这提供了相同的结果。总是用语言标记问题。@JohnnyMopp抱歉,忘了!谢谢你的提醒请不要诋毁你的问题。
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