Code covered by the BSD License  

Highlights from
repositionStructField

from repositionStructField by Georg D
a bit more convenient way to reposition fields in a structure

repositionStructField(s,shiftfield,newpos)
function [s] = repositionStructField(s,shiftfield,newpos)
%shiftfield can be fieldname (string) or current position index of field
%newpos can be either new position index of field, or the name of the field (as string) that is
%currently occupying the new position

allfields = fieldnames(s);
structsize = numel(allfields);
if isnumeric(shiftfield)
    shiftfieldind = shiftfield;
    shiftfieldstr = allfields{shiftfield};
else
    shiftfieldstr = shiftfield;
    for ii = 1:numel(allfields)
        if strcmp(allfields{ii},shiftfieldstr)
            shiftfieldind = ii;
            break;
        end
    end
end

if ~isnumeric(newpos)
    for ii = 1:structsize
        if strcmp(allfields{ii},newpos)
            newpos = ii;
            break;
        end
    end
end

allfields(shiftfieldind)=[];

if newpos==1
    allfields = [shiftfieldstr;allfields];
elseif newpos==structsize
    allfields = [allfields;shiftfieldstr];
else
    allfields = [allfields(1:newpos-1);shiftfieldstr;allfields(newpos:end)];
end


s = orderfields(s,allfields);


Contact us