MATLAB: Obtaining contents of a column in a table corresponding to specific contents of another column in the same table

data acquisitionfor loop

Hello,
I have a table similar to the table provided below:
col1 = ['n1'; 'n2'; 'n3'; 'n4';'n5'; 'n6'; 'n7'; 'n8'; 'n9'];
col2 = [1.1; 1.2; 1.3; 2.1; 2.2; 2.3; 1.1; 2.2; 3.3];
col3 = [1;1;1;2;2;2;3;3;3];
T = table(col1, col2, col3);
I have two other matrices similar to the following
X = [1,2,3];
a = [1.1, 2.3, 2.2];
I would like to obtain only those contents of col1 of table T, that correspond to values in col2 which are equal to the values in 'a' and when the values of col3 match a value in matrix X
Meaning, I would like to obtain a folder, say 'aFile', that has the following content
cola = ['n1'; 'n6'; 'n8'];
colb = a';
aFile = table(cola,colb);
I use a for loop of the following
num = numel(X);
aFile = cell(num,3);
for n = 1:num & T.col3 == 1:num
r = find(T.col2 == a(n));
aFile{n,1} = T(r,1);
aFile{n,2} = T(r,2);
end
But I don't recieve anything in aFile folder. Furthermore, I recieve an error
Row index exceeds table dimensions. at line aFile{n,1} = T(r,1);
How should I modify my code?

Best Answer

You shouldn't use a loop for this sort of things. Operate on the whole columns at once:
col1 = ['n1'; 'n2'; 'n3'; 'n4';'n5'; 'n6'; 'n7'; 'n8'; 'n9'];
col2 = [1.1; 1.2; 1.3; 2.1; 2.2; 2.3; 1.1; 2.2; 3.3];
col3 = [1;1;1;2;2;2;3;3;3];
T = table(col1, col2, col3);
X = [1,2,3];
a = [1.1, 2.3, 2.2];
%Note that the following uses implicit expansion, so X and a MUST be row vectors (or compatible),
%see https://www.mathworks.com/help/matlab/matlab_prog/compatible-array-sizes-for-basic-operations.html
aFile = T(any(T.col2 == a & T.col3 == X, 2), [1 2])
I've not looked at your loop to see what is wrong with it.