How programmatically create an array from variable-length vectors?

6 次查看(过去 30 天)
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 个评论
Voss
Voss 2024-5-29
@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.

请先登录,再进行评论。

采纳的回答

Voss
Voss 2024-5-29
If each .mat file contains a structure called "s1" which contains a field "a" which is what you are interested in:
F = dir('*.mat');
for ii = 1:numel(F)
S = load(fullfile(F(ii).folder,F(ii).name));
F(ii).a = S.s1.a;
end
result = [F.a];

更多回答(1 个)

Dyuman Joshi
Dyuman Joshi 2024-5-29
编辑:Dyuman Joshi 2024-5-29
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{:}];

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by