1

I have a structure array:

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

and so on

How do I swap all the values of field1 with all the values of field2?

I've tried this code

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

And while I can get the field2 values into field1, I can't get the field1 values into the field2.

3
  • Always tag you questions with a language. Commented Aug 3, 2016 at 14:43
  • @JohnnyMopp sorry, forgot! Thanks for the reminder Commented Aug 3, 2016 at 14:45
  • 3
    Please do not deface your question. Commented Aug 3, 2016 at 17:34

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.