Merge same field of 36 structures

1 次查看(过去 30 天)
nlm
nlm 2019-3-7
I want to merge same field (e.g., long which is a matrix) from 36 structures of lenghth (266) which has 20 fields for each structure For example, I have structures S1, S2, S3, S4, S4 ... S36 etc of length varying between 266 to 306 with same field names lat, long, date, temp, air etc which are matrices of variable length varying from [1500 to 15000 by 7]. I want to merge S1 to S36 of field "long" and "date", i.e., S = [S1.long, S2.long, ...].The error I receive for the below code is, "Reference to non-existent field 'long'.
numfiles = length(filenames);
results = cell(numfiles, 1);
U1 =[];
for K = 1 : numfiles
thisfile = filenames{K};
datastruct = load(thisfile);
xyz = datastruct.long; %extract particular variable
processed_xyz = vertcat(U1,xyz); %call appropriate function to handle the data
results{K} = processed_xyz;
end
This is suggested by a matlab user, however when I implement it it does not recognize the long field in the datastruct structure.
  4 个评论
per isakson
per isakson 2019-3-7
Did you try
xyz = datastruct.S1.long;
Did you inspect datastruct in the Variable Editor?
nlm
nlm 2019-3-7
编辑:Walter Roberson 2019-3-7
This works,
xyz = datastruct.S1.long;
However, I want to run it in loop for 36 STRUCTURES.

请先登录,再进行评论。

回答(1 个)

per isakson
per isakson 2019-3-7
编辑:per isakson 2019-3-7
Try this
%%
numfiles = length(filenames);
results = cell(numfiles, 1);
for K = 1 : numfiles
datastruct = load( filenames{K} );
U1 = zero( 0, 7 );
for jj = 1 : 36
U1 = vertcat( U1, datastruct.(sprintf('S%d',jj)).long ); %#ok<AGROW>
end
results{K} = U1;
end
  7 个评论
per isakson
per isakson 2019-3-7
编辑:per isakson 2019-3-7
I now assume that
whos( '-file', filenames{2} )
will output S2, et cetera
"This is the full message" IMO: it's much easier to debug functions than scripts.
I assume that the error was caused by jj being empty
>> jj = [];
>> sprintf('S%d',jj)
ans =
'S'
per isakson
per isakson 2019-3-7
Maybe, this works
function results = ccsm( filenames )
%%
numfiles = length(filenames);
results = cell(numfiles, 1);
for K = 1 : numfiles
datastruct = load( filenames{K} );
U1 = zero( 0, 7 );
for jj = 1 : length( datastruct.(sprintf('S%d',K) ) )
U1 = vertcat( U1, datastruct.(sprintf('S%d',K))(jj).long ); %#ok<AGROW>
end
results{K} = U1;
end
end

请先登录,再进行评论。

Community Treasure Hunt

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

Start Hunting!

Translated by