Azzera filtri
Azzera filtri

Merge same field of 36 structures

1 visualizzazione (ultimi 30 giorni)
nlm
nlm il 7 Mar 2019
Commentato: per isakson il 7 Mar 2019
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 Commenti
per isakson
per isakson il 7 Mar 2019
Did you try
xyz = datastruct.S1.long;
Did you inspect datastruct in the Variable Editor?
nlm
nlm il 7 Mar 2019
Modificato: Walter Roberson il 7 Mar 2019
This works,
xyz = datastruct.S1.long;
However, I want to run it in loop for 36 STRUCTURES.

Accedi per commentare.

Risposte (1)

per isakson
per isakson il 7 Mar 2019
Modificato: per isakson il 7 Mar 2019
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 Commenti
per isakson
per isakson il 7 Mar 2019
Modificato: per isakson il 7 Mar 2019
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 il 7 Mar 2019
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

Accedi per commentare.

Community Treasure Hunt

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

Start Hunting!

Translated by