How to preallocate memory for storing data in same mat file?
Show older comments
Hi, I wrote the below code and I would like to preallocate memory so that the code will run faster. Once I preallocate I know that I cannot use append but need to index to store output. Can you suggest how to get output for code below?
Here the value of f is a 1*5449 double. Final output is 5449*5449 double.
clc;
n=1; %system order
m=1; %number of inputs
p=6;%number of outputs
Final = [];
for i = 1:7783
for j = 1:50
if exist(['ID_',num2str(i),'_file_',num2str(j),'_Variables','.mat'],'file')
load(['ID_',num2str(i),'_file_',num2str(j),'_Variables','.mat']);
A1 = A{1};
A1 = A1 / max(abs(eig(A1)));
B1 = B{1};
C1 = C{1};
index = 1;
for k = 1:7783
for l = 1:50
if exist(['ID_',num2str(k),'_file_',num2str(l),'_Variables','.mat'],'file')
load(['ID_',num2str(k),'_file_',num2str(l),'_Variables','.mat']);
A2 = A{1};
A2 = A2 / max(abs(eig(A2)));
B2 = B{1};
C2 = C{1};
f(index) = distance1_matlab(A1,A2,B1,B2,C1,C2);
index = index + 1;
end
end
end
Final = [Final;f];
end
end
end
save('Distance','Final');
5 Comments
madhan ravi
on 20 Oct 2018
upload your data file
Sunny
on 20 Oct 2018
As commented in your other question, preallocation right now is the least of your worries. Your problem is the unnecessary 29,691,601 (29 millions!) file read (for 5449 files) and associated eig calculations.
Also, since only 5449 files actually exist out of the 389,150 that you're testing it would be simpler to just ask the OS for the list of files in the directory. Is there any other mat files in that directory and if yes, do these extra files match the pattern ID_*file_*_Variables or not? Answering no to either question will simplify things.
Also, what is the size of cell arrays A, B and C (useless names!) in each mat file? (And why is the data stored in a cell array if you only use one cell?)
Oh, and what is the function distance1_matlab?
Guillaume
on 21 Oct 2018
Well, yes it's going to be much faster. You're reading each file only once. You're still doing N^2 unnecessary eigs and related calculations. And nearly 99% of the files you test for existence don't exist, so it'd be faster to do a dir so the OS just tells you which files are there.
Finally, depending on what distance1_matlab does, it may well be that your 2nd loop is not needed.
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements 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!