Preallocation of a vector of structure
2 views (last 30 days)
Show older comments
Hello everyone,
I've been trying to preallocate a vector in which each cell will be a structure of 42 fields like thi:
data = zeros(1,9);
for i=1:9
if(i~=5)
data(i) = load(['DPsv0000',num2str(i),'.mat']);
end
end
Because I need the nine different structures in the same vector for the rest of the code and I want it to be time efficient. However, I can't seem to find a way for the preallocation to work. In fact, doing this, I get the following error:
Conversion to double from struct is not possible.
Error in MECA0062_Gaspar_1 (line 135)
data(i) = load(['DPsv0000',num2str(i),'.mat']);
Can anyone know if it is even possible to do what I'm trying?
Thanks everyone, have a good day!
Audric
0 Comments
Answers (3)
dpb
on 7 Nov 2020
You preallocated a double array and then tried to put a struct variable into it. As you discovered, "You can't do that!"
There's not the equivalent per se of preallocating a struct array of empty array elemnts; you just iterate and go on...
d=dir('DPsv0000*.mat']); % return desired .mat files directory listing
for i=numel(d)
if contains(d(i).name,'5'), continue, end
data(i)=load(d(i).name);
end
0 Comments
Peter Perkins
on 20 Nov 2020
Audric, it seems like dpb understand what you are doing better than I do, but "in which each cell will be a structure of 42 fields" sounds like maybe you are overcomplicating, and that you want an Nx42 table.
0 Comments
Stephen23
on 20 Nov 2020
n = 9;
P = 'absolute or relative path to where the files are saved';
C = cell(1,n);
V = setdiff(1:n,5);
for k = V
F = sprintf('DPsv%05d.mat',k);
C{k} = load(fullfile(P,F));
end
S = [C{:}]
0 Comments
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!