Adding multiple fields and values to structure array

95 ビュー (過去 30 日間)
Centauri Jolene
Centauri Jolene 2019 年 4 月 19 日
コメント済み: Centauri Jolene 2019 年 4 月 20 日
I have a code in which I am looping through many files, and for each file, I'm adding fields and values to a structure array.
The code is quite repetitive and I'm wondering if there is a way to shorten it a bit.
Right now it looks like this:
data(k).pairNum = pairNum;
data(k).level = level;
data(k).trialNum = trialNum;
data(k).success = win;
data(k).numWins = numWins;
data(k).totalTime = totalTime;
data(k).timeUntilSuccess = timeUntilSuccess;
data(k).totalTime = totalTime;
data(k).initialSpread = initialSpread;
data(k).initialCOM = initialCOM;
data(k).D1_distance = D1_distance;
data(k).D2_distance = D2_distance;
But im just curious if there is a way to make it work by doing something like this:
data(k).[pairNum, level, trialNum, win, numWins, totalTime] = pairNum, level, trialNum, win, numWins, totalTime;
  2 件のコメント
Stephen23
Stephen23 2019 年 4 月 19 日
編集済み: Stephen23 2019 年 4 月 19 日
One easy way to avoid this would be to define those variables as fields of a scalar structure S, rather than as separate variables. Then merging them with the non-scalar output structure is just one simple assignment data(k) = S;
Centauri Jolene
Centauri Jolene 2019 年 4 月 20 日
I dont 100% understand what you mean, could you elaborate? Sorry, I'm a bit of a novice...

サインインしてコメントする。

採用された回答

Walter Roberson
Walter Roberson 2019 年 4 月 19 日
Provided you are setting all of the fields of data(k), then you can use
data(k) = struct('PairNum', pairNum, 'level', level, 'trialNum', trialNum, ....)
which is no shorter.
Or you could use
names = {'pairNum', 'level', 'trialNum', 'success' ... };
and then in the loop
data(k) = cell2struct( {pairNum, level, trialNum, win, ...}, names, 2);
Again, these only work if you are setting all of the fields.
If you have all of the values ahead of time you can create the entire struct:
data = struct('PairNum', cell_with_all_pairnum, 'level', cell_with_all_level, ....)
The number of structure members created will be the same as the number of entries in the cells you pass.
If any of the fields are the same for all of the members, then instead of a cell, you can pass the actual value at that location, not in a cell.
  1 件のコメント
Centauri Jolene
Centauri Jolene 2019 年 4 月 19 日
Thank you! Great answer.
I have over 50 fields so I may just stick with individual lines for each field, to avoid oner super long line of code.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

製品


リリース

R2017b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by