You're pretty much there with your approach. The simplest fix would be to store a as a cell array, rather than a numeric array, in order to take advantage of MATLAB's list expansion:
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{:};
Where [s.field1; s.field2] goes from:
ans =
11 21
12 22
To:
ans =
12 22
11 21
For a more general approach, you could utilize struct2cell and cell2struct to swap the fields:
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
Which provides the same result.