How to speed up operation in two 'for' loops?
2 views (last 30 days)
Show older comments
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1230532/image.png)
Only k cycles take 20 seconds,it will waste more time with i cycle.How can I improve?
0 Comments
Accepted Answer
Stephen23
on 14 Dec 2022
Edited: Stephen23
on 14 Dec 2022
"How can I improve?"
In general importing/exporting data is slow. So rather than calling READMATRIX 58732*numel(S) times in a loop, just call READMATRIX numel(S) in a loop and manipulate the imported matrices in MATLAB memory. Your code will also be slow because NUM is not preallocated:
The second (58732) loop looks superfluous (you just seem to be allocating scalars to NUM), so most likely you can you efficiently concatenate the imported vectors/matrices after the loop.
P = 'D:\elevation';
S = dir(fullfile(P,'*.dat'));
for k = 1:numel(S)
F = fullfile(S(K).folder,S(k).name);
M = readmatrix(F);
S(k).data = M(:,6);
end
A = [S.data].'
Note that depending on the filenames, the order of files returned by DIR() might not what you expect (and so your concatenated data might not be in the order you expect).
4 Comments
Stephen23
on 15 Dec 2022
Edited: Stephen23
on 15 Dec 2022
"How to convert longitude and latitude coordinate axis to xy coordinate"
Is this what you are looking for?:
N = 301;
X = linspace(110,130,N)
Y = linspace(35,42.2,N)
Note that 1:300 is only 299 equal parts, see https://en.wikipedia.org/wiki/Off-by-one_error#Fencepost_error
Or perhaps you want to convert lat/long data into X/Y data, e.g.:
V = 35+(42.2-35)*rand(1,7) % random latitude data with range from 35 to 42.2
X = interp1([35,42.2],[1,N],V) % converted to range from 1 to 301
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices 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!