how to initialise field name of struct array?
11 ビュー (過去 30 日間)
古いコメントを表示
I want to set some fields of a struct array, like .name .age .id then I want to put data in one line. Is it possible to do something like this?
% initialise data struct with fields .name, .age, .id in this order, than put data like this:
data(1) = ... ('John',12,'ABC123') ... ;
The result what I want is this:
data(1).name = 'John';
data(1).age = 12;
data(1).id= 'ABC123';
0 件のコメント
採用された回答
Guillaume
2015 年 10 月 12 日
data = cell2struct({'John', 12, 'ABC123'}, {'name', 'age', 'id'}, 2)
2 件のコメント
Guillaume
2015 年 10 月 12 日
編集済み: Guillaume
2015 年 10 月 12 日
You can initialise the whole array at once:
data = cell2struct({'John', 12, 'ABC123'; 'Adam', 15, 'DEF456'; 'Lucy', 7, 'XXX000'}, {'name', 'age', 'id'}, 2)
IIf your struct array already exists and you want to initialise another element, you can use fieldnames to retrieve the names of the fields:
data = struct('name', {}, 'age', {}, 'id', {}); %creates an empty struct with fields
data(1) = cell2struct({'John', 12, 'ABC123'}, fieldnames(data), 2);
data(2) = cell2struct({'Adam', 15, 'DEF456'}, fieldnames(data), 2);
data(3) = cell2struct({'Lucy', 7, 'XXX000'}, fieldnames(data), 2);
その他の回答 (1 件)
Walter Roberson
2015 年 10 月 12 日
Only in the case where you initialize all of the fields for the structure.
% initialise data struct with fields .name, .age, .id in this order, than put data like this:
data(1) = struct('name', 'John', 'age', 12, 'id', 'ABC123');
Or you can use cell2struct as shown by Guillaume, which will have the same restriction that every entry you do this for must have the same fields in the same order.
If you want a more compact syntax then you should consider using a small function (could be anonymous) which expands the syntax; you should also consider using Object Oriented Programming, in which case you would be calling a Constructor for your class.
6 件のコメント
Walter Roberson
2015 年 10 月 12 日
Huh? I just showed you how to do it using a small function. If writing INI is too much then you can use a shorter name.
S = @(name, age, id) struct('name', name, 'age', age, 'id', id);
data(1) = S('John', 12, 'ABC123');
data(2) = S('Fred', 37, 'PQ19B');
data(3) = S('Kansola', 5, 'ZZ9 plural Z alpha');
Guillaume
2015 年 10 月 12 日
Much of the skill of writing code is not only in making it work but also in making it readable for whoever is going to maintain it. As such, using shortcuts that make it easier to write the code but make it difficult to understand should be avoided.
Code it typically, write once, read many. The read many is what needs to be optimised, not the write once.
参考
カテゴリ
Help Center および File Exchange で Structures についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!