MATLAB: Erase data assigned to the variables for every iteration of the FOR LOOP

for loop

Hi,
I have 6 table data with each of size 2000×100 with a random 1 & 0. I would like to sum all these 6 table data using a for loop and if the sum is less than 100 then i skip the particular case. If the sum is equal to 100 then i write that specific case to a new variable.
Now the issue is the Variable to combine and sum these 6 table data does not start at first row during each iteration. Instead they get shifted down by 1 row everytime.
I have pasted a sample code below, someone please help me fix it.
Sample Code: (I am just displaying 2 table variables)
K = 20
for i = 1:1:K
x1(i,:) = a1{i,:};
x2(i,:) = a2{i,:};
Threshold = [x1; x2];
Sum = sum(Threshold,2)';
clear Threshold
if Sum == 26
y1(i,:) = x1{i,:};
y2(i,:) = x2{i,:};
clear Sum
else
i = i +1;
clear Sum
end
clear x1 x2
end

Best Answer

First, let's fix your starting point. As I said, for what you're doing tables are the wrong storage. They're more complicated to use and use more memory. Ideally, you'd go back to whichever code created your a tables so that a) they're not numbered and b) they're matrices. So instead of tables, we're going to use matrices. Since your matrices are 2D and have all the same size, the simplest is to store them all in a single 3D matrices:
allmatrices = cat(3, table2array(a1), table2array(a2), table2array(a3), table2array(a4), table2array(a5), table2array(a6));
Numbered variables forces you to repeat the same code many times, as you can see above. Always a bad idea...
I'm still unclear of your goal.
If you want to keep only the rows that are all ones, it's simply:
selectedrows = allmatrices(all(allmatrices == 1, [2 3]), :, :); %keep rows that are all 1 across columns and matrices. This syntax requires R2018b or later
which will output a ?x100x6 matrix with only the rows containing all ones.
If you want to keep only the rows that sum to 100, it's simply:
selectedrows = allmatrices(sum(allmatrices, [2 3]) = 100, :, :); %keep only the rows that sum to 100 across the columns and matrices. Syntax requires R2018b or later