Clear Filters
Clear Filters

More effective code than loop that takes a lot of time

1 view (last 30 days)
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 Comments
Steven Lord
Steven Lord on 8 Feb 2018
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 on 9 Feb 2018
Edited: Aletta Wilbrink on 9 Feb 2018
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.

Sign in to comment.

Answers (1)

Prajit T R
Prajit T R on 22 Feb 2018
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

Community Treasure Hunt

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

Start Hunting!