Preallocation of a vector of structure

2 次查看(过去 30 天)
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

回答(3 个)

dpb
dpb 2020-11-7
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

Peter Perkins
Peter Perkins 2020-11-20
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.

Stephen23
Stephen23 2020-11-20
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{:}]

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by