问题
I'm working on a matlab code where I have a lot of variables that need to be preallocated (each variable is 8760x1 double). The values are generated in a for loop:
a=zeros(8760,1);
b=zeros(8760,1);
(...)
for i=1:8760
a(i)=[some code];
b(i)=[some code];
(...)
end
However, seeing that I have a lot of these variables, I want to preallocate the parameters in another file (more clean).
preallocate.m
a=zeros(8760,1);
b=zeros(8760,1);
...
main.m
preallocate
for i=1:8760
a(i)=[some code];
b(i)=[some code];
(...)
end
Will preallocating in another matlab file be as efficient as doing it in the same file as the executing file? Other suggestions?
回答1:
Yes.
回答2:
This is a valid approach, but you must make sure that your variables make it to the workspace of your main function, i.e. you should set up the preallocate.m such that:
[a, b] = preallocate
that way when it is called in the main function, your preallocations will be initialized.
来源:https://stackoverflow.com/questions/28941601/matlab-can-a-large-number-of-preallocations-be-placed-in-another-file