Clear Filters
Clear Filters

How to speed up operation in two 'for' loops?

1 view (last 30 days)
Only k cycles take 20 seconds,it will waste more time with i cycle.How can I improve?

Accepted Answer

Stephen23
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
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)
X = 1×301
110.0000 110.0667 110.1333 110.2000 110.2667 110.3333 110.4000 110.4667 110.5333 110.6000 110.6667 110.7333 110.8000 110.8667 110.9333 111.0000 111.0667 111.1333 111.2000 111.2667 111.3333 111.4000 111.4667 111.5333 111.6000 111.6667 111.7333 111.8000 111.8667 111.9333
Y = linspace(35,42.2,N)
Y = 1×301
35.0000 35.0240 35.0480 35.0720 35.0960 35.1200 35.1440 35.1680 35.1920 35.2160 35.2400 35.2640 35.2880 35.3120 35.3360 35.3600 35.3840 35.4080 35.4320 35.4560 35.4800 35.5040 35.5280 35.5520 35.5760 35.6000 35.6240 35.6480 35.6720 35.6960
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
V = 1×7
36.3694 38.5863 38.5112 37.4681 38.4170 36.8725 39.7453
X = interp1([35,42.2],[1,N],V) % converted to range from 1 to 301
X = 1×7
58.0568 150.4295 147.3018 103.8379 143.3761 79.0208 198.7210
ke
ke on 15 Dec 2022
I have a matrix data of '331 × 331 double'. If 330 copies of the horizontal and vertical coordinates of the image are divided equally, each point in the image corresponds to one data. So I don't know how to divide it?

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!