More effective code than loop that takes a lot of time

1 次查看(过去 30 天)
I have a table T with over 300.000 rows and 39 columns.
I also have a table T2 with 8.800 rows, which is a subtable of T:
T2 = T(T.b > 1,:);
Now I have written a loop, shown below, which does exactly what I want, but takes a lot of time.
T2.z = zeros(height(T2),1);
for i = 1:height(T2)
var1 = ismember(T3(:,[24 30]), T2(i,[24 30])) & T3.b == 1;
var2 = T3.a(var1);
if isempty(var2)
else
var3 = T3.c(var1);
var4 = T3.d(var1);
if var2 ~= -1
T2.z(i) = datenum(var3 + var2);
else
T2.z(i) = datenum(var3 + var4);
end
end
end
T2.z = datetime(T2.z, 'ConvertFrom', 'datenum');
TTrials.Trialshort(TTrials.Trialshort == datetime('31-Dec--0001 00:00:00')) = NaT;
I know loops aren't the most effective ways in MATLAB, but I don't know how to do this different. Can someone help?
What I want to do in words:
I have a table with data. Each row has a unique combination of 3 columns (say c1, c2 and b (I called it b in the code)), b contains the trialnumber.
T2 is a table with only the records with trial number 2 or higher. Now I want to add a column is this table where z is the addition of 2 other columns in T (a date and a number (amount of days)), of the record in T with the same values for c1 and c2, but where b = 1.
  7 个评论
Steven Lord
Steven Lord 2018-2-8
Would it be possible for you to explain in words (not code) what you're trying to do? It's possible that we can find a more effective way to achieve your goal if we focus on what you're trying to do rather than how this particular implementation tries to achieve that goal.
Aletta Wilbrink
Aletta Wilbrink 2018-2-9
编辑:Aletta Wilbrink 2018-2-9
I have a table with data. Each row has a unique combination of 3 columns (say c1, c2 and b (I called it b in the code)), b contains the trialnumber.
T2 is a table with only the records with trial number 2 or higher. Now I want to add a column is this table where z is the addition of 2 other columns in T (a date and a number (amount of days)), of the record in T with the same values for c1 and c2, but where b = 1.
I hope this is clear to you.

请先登录,再进行评论。

回答(1 个)

Prajit T R
Prajit T R 2018-2-22
Hey Aletta
Upon reading your question I get the impression that what you're trying to do is a typical database operation. You may want to check out Database toolbox If you still want to use for loop, you will be better off using the parfor loop provided you have access to the Parallel Computing toolbox. Parallel Computing toolbox
Cheers

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by