开发者

MATLAB: is fieldnames' order defined?

For the same input structure, will fieldnames always return the same cell array, even on different computers, different OS's, and different MATLAB versions? Or coul开发者_开发百科d it order the field names differently? E.g.:

myStructure = load myStructure;
x = fieldnames(myStructure);

% days later, diff computer, diff OS, and diff version of MATLAB...
y = fieldnames(myStructure);
x == y %?

The documentation for fieldnames does not seem to promise that the same order is returned every time. But on the other hand, the existence of orderfields seems to imply that fieldnames predictably returns an underlying, normally unchanging order.


I believe the structure fields are ordered as they created. If you save the structure into mat-file and open it later with another MATLAB, the order will be kept. You can always reorder fields with ORDERFIELDS function. You can order in many different ways (sort alphabetically, using a cell arrays, another structure or permutation vector), see the documentation for more details.

By the way, fields order does not affect structures comparison.

s1 = struct('a',0,'b',1)

s1 = 

    a: 0
    b: 1

s2 = struct('b',1,'a',0)

s2 = 

    b: 1
    a: 0

isequal(s1,s2)

ans = 

     1

s1=orderfields(s1,s2)

s1 = 

    b: 1
    a: 0

UPDATE:

Here is the quote from the MATLAB documentation for structure data type under "Listing the Fields of a Structure" subtitle:

The fields appear in the order in which they were created.

Hope this answers your question.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜