How to select specific data from a structure

150 次查看(过去 30 天)
Hi, I have the following structure: data.variation_#.ts
- data has 23 variation fields (i.e. variation_1, variation_2 etc.), and I'm interested in field 3 to 23
- The ts field is a 30x10800 double
How can I read throug the variation fields of interest(3 to 23) and for all of them get some of the rows from ts (for example rows 2 3 4, all columns)
Thanks
  1 个评论
dpb
dpb 2016-6-21
"... following structure: data.variation#.ts"_
Bad idea here is your basic problem. Instead of sequentially-named fields of 2D array, use 3D array where each variation is a plane. Then you simply refer to the planes of interest.

请先登录,再进行评论。

回答(2 个)

Guillaume
Guillaume 2016-6-22
This is why I think it's not a good idea to recommend using dynamic field names instead of eval, it leads to the same problems.
If you have numbered variables or field names, you have a poor data structure and it indeed becomes difficult to operate the same process on all of them at once. The proper solution is to get rid of all these numbered variables / field names and store their content into a cell array (if the size of the content varies from variable to variable) or a matrix (if not). It is then trivial to index them.
See Jos' answer for a good structure. However, personally I would avoid the multilevel structure, it's a pain to work with (See my comment to Jos' answer).
Assuming that the variation fields are the only field of data, you can convert your existing structure into Jos' suggestion with:
newdata.variation = cell2mat(struct2cell(data))
%or you could just do
variation = cell2mat(struct2cell(data))
%and not bother with multilevel structures
To then get rows [3 4 8] of variations 3 to 23 as a 3d array:
selectedts = cat(3, variation(3:23).ts);
selectedrows = selectedts([3 4 8], :, :);
  2 个评论
Isma_gp
Isma_gp 2016-6-22
Hei, the variation fields are not the only fields of data. Is there any way to convert the data then?
Thanks
Guillaume
Guillaume 2016-6-22
Probably, the safest way to do this:
wantedfields = sprintfc('variation_%d', 3:23);
[~, fieldrows] = ismember(wantedfields, fieldnames(data));
dataascell = struct2cell(data);
variations = cell2mat(dataascell(fieldrows));
selectedts = cat(3, variation(3:23).ts);
selectedrows = selectedts([3 4 8], :, :);

请先登录,再进行评论。


Jos (10584)
Jos (10584) 2016-6-22
Store your data like this
data.variation(1).values = ..
data.variation(2).values = ..
data.variation(3).values = ..
which makes it trivial to select the fields you need
data.variation([3 4 8])
It is the content of a variable (or field) that is supposed to be flexible, not its name!
  3 个评论
Shahram
Shahram 2022-12-16
Thanks "data.variation([3 4 8])" worked wel

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by