How programmatically create an array from variable-length vectors?
Mostra commenti meno recenti
Hello
I have ~500 .mat files, generated by a separate software, which all contain a structure called s1.a. This structure has variable length for each file, and I don't know this length until each file is loaded into the workspace. I cannot control the naming of the files nor the naming of the structures ahead of time. Example:
s1.a = [1 3 4 2];
s1.a = [4 6 2 9 0 4];
s1.a = [0 9 5 7 2];
s1.a = [4 8 6 1];
s1.a = [5 7 2 9 4 0 1];
...
s500.a = [3 2 0];
I need to end up with a single structure at the end which concatenates all of the individual s1.a structures:
sFinal.a = [1 3 4 2 4 6 2 9 0 4 0 9 5 7 2 4 8 6 1 5 7 2 9 4 0 1 ... 3 2 0];
If all structures had the same length, I can easily write a for loop to load each file and then build the array. But I'm struggling with the variable length aspect of each structure.
One thought I had was to pre-allocate an array with NaNs that is longer than the max length of the s1.a structure (which is 3600), thus "forcing" them to be of the same length by populating the first numel(s1.a) slots, and then once the final structure is built, simply removing all the NaNs. But this seems rather convoluted and not efficient.
Any suggestions?
Thank you!
3 Commenti
David Velasco
il 29 Mag 2024
Voss
il 29 Mag 2024
@David Velasco: You're welcome!
"I had to modify the last command, as each structure has variable length, so the catenation as you have it doesn't work."
The problem was not the variable length, but that the vectors are column vectors instead of row vectors as described in the question.
"had to change last line to "result = cat(1.F.a);""
I guess you mean "result = cat(1,F.a);" (note the comma). You could've also used vertcat.
David Velasco
il 29 Mag 2024
Risposta accettata
Più risposte (1)
Dyuman Joshi
il 29 Mag 2024
Modificato: Dyuman Joshi
il 29 Mag 2024
Here's a method to import data from a sequence of files -
%Read all the mat files in the directory
Files = dir('*.mat');
%Total number of files
numfiles = length(Files);
%Preallocate a cell array
in = cell(1, numfiles);
for k = 1:numfiles
%Store the data into cell elements iteratively
in{k} = (Files(k).s.a1);
end
%Concatenate the data horizontally to obtain
%the desired output
out = [in{:}];
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!