2016-08-03 45 views
1

我有一個結構數組:交換字段的值在一個結構數組

s(1)=struct('field1', value, 'field2', value, 'field3', value) 
s(2)=struct('field1', value, 'field2', value, 'field3', value) 

如何交換FIELD1的所有值與域2的所有值?

我試過這個代碼

a=[s.field1]; 
[s.field1]=s.field2; 
[s.field2]=a; 

雖然我可以得到場2的值到字段1,我不能讓FIELD1值到域2。

+0

總是用語言標記問題。 –

+0

@JohnnyMopp對不起,忘記了!感謝提醒 –

+2

請不要污衊你的問題。 – JAL

回答

2

你幾乎在那裏用你的方法。最簡單的解決將是存儲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 

對於一個更通用的方法,你可以UT斯達康ilize struct2cellcell2struct交換領域:

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 

它提供了相同的結果。

相關問題