필터 지우기
필터 지우기

Merge same field of 36 structures

조회 수: 1 (최근 30일)
nlm
nlm 2019년 3월 7일
댓글: per isakson 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