Accessing data within a structure

1 回表示 (過去 30 日間)
Christian Tieber
Christian Tieber 2019 年 7 月 15 日
編集済み: Jan 2019 年 7 月 16 日
I have this structure:
veh(x).meas(y).data.fileName
So i have a certain number x of vehicles (veh) and a certain number y of measurements (meas).
how can i get the fileName for every measurement as a list? (efficient)
Would like ot avoid a construct of numerous "numel" and "for" commands.
thanks!

採用された回答

Jan
Jan 2019 年 7 月 16 日
編集済み: Jan 2019 年 7 月 16 日
The chosen data structure demands for loops. There is no "efficient" solution, which extracts the fields in a vectorized way. You can at least avoid some pitfalls:
fileList = {};
nVeh = numel(veh);
for k = 1:nVeh
aVeh = veh(k);
nMeas = numel(aVeh.meas);
for kk = 1:nMeas
fileList{end+1} = aVeh.meas(kk).data.fileName;
end
end
Here the output grows iteratively. If you know a maximum number of elements, you can and should pre-allocate the output:
nMax = 5000;
fileList = cell(1, nMax);
iList = 0;
nVeh = numel(veh);
for k = 1:nVeh
aVeh = veh(k);
nMeas = numel(aVeh.meas);
for kk = 1:nMeas
iList = iList + 1;
fileList{iList} = aVeh.meas(kk).data.fileName;
end
end
fileList = fileList(1:iList); % Crop ununsed elements
Choosing nMax too large is very cheap, while a too small value is extremely expensive. Even 1e6 does not require a remarkable amount of time.
numel is safer than length. The temporary variable aVeh safes the time for locating veh(k) in the inner loop repeatedly.
If you do not have any information about the maximum number of output elements, collect the data in pieces at first:
nVeh = numel(veh);
List1 = cell(1, nMax);
for k = 1:nVeh
aVeh = veh(k);
nMeas = numel(aVeh.meas);
List2 = cell(1, nMeas);
for kk = 1:nMeas
List2{kk} = aVeh.meas(kk).data.fileName;
end
List1{k} = List2;
end
fileList = cat(2, List1{:});

その他の回答 (1 件)

Le Vu Bao
Le Vu Bao 2019 年 7 月 15 日
編集済み: Le Vu Bao 2019 年 7 月 15 日
I have just had the same kind of question. I think you can try a nested table, struct for your data. With table, it is simpler to query for data without using "for" or "numel"
  1 件のコメント
Christian Tieber
Christian Tieber 2019 年 7 月 16 日
Did it with loops at the end. Not very elegant. But it works.
fileList=[]
nVeh=length(veh)
for i=1:nVeh
nMeas=length(veh(i).meas)
for a=1:nMeas
fileName = {veh(i).meas(a).data.fileName}
fileList=[List;fileName]
end
end

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

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by