Increase the number of fields within a 'for' loop?
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Julia Horne
am 15 Mär. 2018
Kommentiert: Julia Horne
am 19 Mär. 2018
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 Kommentare
Akzeptierte Antwort
Guillaume
am 16 Mär. 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
Weitere Antworten (1)
per isakson
am 16 Mär. 2018
Bearbeitet: per isakson
am 16 Mär. 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 Kommentare
per isakson
am 17 Mär. 2018
- "but it requires that I preallocate the struct" see the answer by Guillaume
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!