Increase the number of fields within a 'for' loop?
조회 수: 3 (최근 30일)
이전 댓글 표시
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
채택된 답변
Guillaume
2018년 3월 16일
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
추가 답변 (1개)
per isakson
2018년 3월 16일
편집: per isakson
2018년 3월 16일
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
per isakson
2018년 3월 17일
- "but it requires that I preallocate the struct" see the answer by Guillaume
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!