Naming individual fields in a struct

조회 수: 2 (최근 30일)
mashtine
mashtine 2014년 2월 24일
편집: Walter Roberson 2014년 2월 24일
Hi everyone,
I have this block of code:
HWFiles = {'midas_wind_197901-197912.txt',............'midas_wind_201301-201312.txt'};
for k=1:numel(HWFiles);
fid = fopen(HWFiles{k}, 'r');
tmp = textscan(fid,'%s %*s %*f %*f %*s %*f %f %*f %f %f %f %f %f %*f %*f %*f %*f %*f %*f %*f %*f %*s %*f', 'Delimiter',',');
HWData(k).data = tmp ;
fclose(fid);
end
Not pasting well sorry. HWData becomes a 1 x 35 struct and I wanted to change each field name to the year from the file, eg 1979, 1980 .... 2013. Any ideas with this?

채택된 답변

Walter Roberson
Walter Roberson 2014년 2월 24일
Are you asking to create a structure of length 1, HWData, with field names 1979, 1980, and so on? If so then you cannot do that as field names must start with a letter. If you wanted to be able to look up by year then you could use a common prefix such as 'Y', so Y1979, Y1980, and so on. Or you could use containers.map
TO use the prefix,
prefix = 'Y';
and in the loop,
filename = HWFiles{k};
underpos = find(filename, '_', 1, 'last');
fieldname = [prefix filename(underpos+1:underpos+3)];
HWData.(fieldname) = tmp;
  댓글 수: 5
mashtine
mashtine 2014년 2월 24일
However, I believe indexing this in a loop to manipulate and work with the data is probably a bit too complicated (or perhaps I just don't know it yet)
Walter Roberson
Walter Roberson 2014년 2월 24일
편집: Walter Roberson 2014년 2월 24일
Opps, should have had
underpos = find(filename == '_', 1, 'last');
Indexing by a non-consecutive number (eg. year) to work in a loop is going to be very nearly as much trouble.
Recall that you can use fieldnames() to get the names of the fields. And sort() of a cell array of strings would give the fieldnames sorted numerically provided they were all the same length.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2014년 2월 24일
If you have R2013b, why not use a table. You can use struct2table to convert your structure to a possibly more convenient table. Table is a brand new data type. http://www.mathworks.com/help/matlab/ref/struct2table.html
  댓글 수: 1
mashtine
mashtine 2014년 2월 24일
I wish I could but I am stuck with R2010 unfortunately.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by