slow for and while loops
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi all, I'm running those lines that suppose to run on two tables (T2 and T1) and check if the difference in the first column is less than coinc_win. both columns in the tables are data from the same clock and I want the code to match line from table T2 to the correspond lines in table T1 and write the lines to T3. this is what I've written so far, but it runs pretty slow, anyone has suggestions how to improve it?
coinc_win = 500;
correction = 150;
j = 1;
r = 1;
tic
for i = 1: height(T2(:,1))
while j <= height(T1(:,1))
while (T2.time(i)+correction) - T1.time(j) > coinc_win || T2.time(i)+correction > T1.time(j)
j = j+1;
break;
end
while T2.time(i) - T1.time(j) < coinc_win && (T2.time(i)+correction) > T1.time(j)
T3.deltaT(r) = T2.time(i) - T1.time(j);
T3.energy_G(r) = T2.E(i);
T3.energy_S(r) = T1.E(j);
r= r+1;
j = j+1;
end
if T2.time(i) < T1.time(j)
break;
end
end
end
toc
12 commentaires
Guillaume
le 24 Jan 2020
A much simpler way to convert a numeric array in nanoseconds to a duration type is with:
dur = seconds(NS * 1e-9);
See example code in my answer.
Réponse acceptée
Guillaume
le 24 Jan 2020
Modifié(e) : Guillaume
le 24 Jan 2020
After looking at it a bit more closely, what you're trying to do is a bit too advanced for synchronize. I would still recommend that you convert to timetable at the end, but for your synchronisation, you'll have to do it manually. Easiest is with ismembertol:
matchwindow = 500; %matching window within which two events are considered equal, in nanoseconds.
S_offset = 150; %offset for S table, in nanoseconds.
G = readtable('T1.txt'); %I would recommend a better name than T1 or G. A name that clearly describes what the table represent
G.Properties.VariableNames = {'Time_G', 'Energy_G'};
S = readtable('T2.txt'); %I would recommend a better name than T1 or S. A name that clearly describes what the table represent
S.Properties.VariableNames = {'Time_S', 'Energy_S'}; %using different variable names so that the tables can be horizontally concatenated
%find intersection of time within the matchwindow and merged the matching rows into a new table
[ismatch, matches] = ismembertol(S.Time_S + S_offset, G.Time_G, matchwindow, 'DataScale', 1); %DataScale is one to make the tolerance absolute
merged = [G(matches(ismatch), :), S(ismatch, :)];
merged.Delta = merged.Time_S - merged.Time_G;
%convert to timetable
merged = convertvars(merged, {'Time_G', 'Time_S', 'Delta'}, @(var) seconds(var * 1e-9));
merged = table2timetable(merged, 'RowTimes', 'Time_G')
edit: spelling
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Data Type Conversion dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!