Increase the number of fields within a 'for' loop?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Julia Horne
el 15 de Mzo. de 2018
Comentada: Julia Horne
el 19 de Mzo. de 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 comentarios
Respuesta aceptada
Guillaume
el 16 de Mzo. de 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
Más respuestas (1)
per isakson
el 16 de Mzo. de 2018
Editada: per isakson
el 16 de Mzo. de 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 comentarios
per isakson
el 17 de Mzo. de 2018
- "but it requires that I preallocate the struct" see the answer by Guillaume
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!