Increase the number of fields within a 'for' loop?
3 views (last 30 days)
Show older comments
I am trying to read a .csv file containing elemental abundances in certain reservoirs, with different units. I want to order this mass of data into a structure that is named 'LITgeo' and contains fields 'species', 'reservoir' and 'unit'. Currently, whenever two different measurements of the same unit go through the loop, the former is replaced by the latter. I want to be able to make my 'unit' field a vector that can contain multiple different measurements in the same units. Here's what I have thus far:
for isp = 1:length(LIT_geosp)
species = LIT_geosp{isp};
reservoir = LIT_geores{isp};
value = LIT_geoval(isp);
unit = LIT_geounit{isp};
LITgeo.(species).(reservoir).(unit)= value ;
end
0 Comments
Accepted Answer
Guillaume
on 16 Mar 2018
I personally don't like multilevel structures. They're often awkward to use and matlab's display interface for them is lacking. Nowadays, I prefer tables even if it means storing redundant information.
If you stick with multilevel structures, you could check if the field(s) already exist and if so, increase the number of elements. If not, create the fields:
species = LIT_geosp{isp};
reservoir = LIT_geores{isp};
value = LIT_geoval(isp);
unit = LIT_geounit{isp};
if isfield(LITgeo, species) && isfield(LITgeo.(species), reservoir) && isfield(LITgeo.(species).(reservoir), unit)
%the test above will bail out as soon as one of the field is not valid because of the short-circuiting behaviour of &&
&if we get here all fields are valid
LITgeo.(species).(reservoir).(unit)(end+1) = value;
else
%at least unit is new
LITgeo.(species).(reservoir).(unit) = value;
end
More Answers (1)
per isakson
on 16 Mar 2018
Edited: per isakson
on 16 Mar 2018
Run
species = 'A';
reservoir = 'B';
unit = 'C';
LITgeo.(species).(reservoir).(unit) = 1;
LITgeo.(species).(reservoir).(unit)(2) = 2;
LITgeo.(species).(reservoir).(unit)(end+1) = 17;
and see the result
>> LITgeo.A.B.C
ans =
1 2 17
2 Comments
per isakson
on 17 Mar 2018
- "but it requires that I preallocate the struct" see the answer by Guillaume
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!