MATLAB: New values not saving in the matrix after each iteration

for loopiterationloopsMATLABtablesupdatevariables

Hi everyone, I'm new to Matlab and trying to help a friend. Basically I have a set of data where I filter only specific columns which are then read via a for loop to find the values that are within certain bounds. Then I want all of them added to a variable, however after each iteration the variable is simply replaced by the next one rather than all kept there. I really searched everywhere and I know it might be a really basic thing but it's better to ask than give up 🙂
dat = readtable('170412E1AM1T0.txt');
dat = dat(:, [1 5]);
dat = dat.Variables;
for i = 1:length(dat)
if 8.5 < dat(i,1) && 8.7 > dat(i,1)
a = dat(i,2);
elseif 12.5 < dat(i,1) && 12.6 > dat(i,1)
b = dat(i,2);
elseif 13.2 < dat(i,1) && 13.4 > dat(i,1)
c = dat(i,2);
elseif 14.5 < dat(i,1) && 14.6 > dat(i,1)
d = dat(i,2);
end
end
Thanks!

Best Answer

You are overwriting the result every iteration, instead of adding it to an existing vector. You could dynamically grow these vectors, but it is better to skip the loop and use logical indexing to directly create the intended vectors. Also, doing a crash course on Matlab can be really useful in getting to know the language.
dat = readtable('170412E1AM1T0.txt');
dat = dat(:, [1 5]);
dat = dat.Variables;
a = dat(8.5 < dat(:,1) & 8.7 > dat(:,1),2);
b = dat(12.5 < dat(:,1) & 12.6 > dat(:,1),2);
c = dat(13.2 < dat(:,1) & 13.4 > dat(:,1),2);
d = dat(14.5 < dat(:,1) & 14.6 > dat(:,1),2);
For your reference, this is the code if you would dynamically grow the vectors:
dat = readtable('170412E1AM1T0.txt');
dat = dat(:, [1 5]);
dat = dat.Variables;
a=[];b=[];c=[];d=[];
for i = 1:length(dat)
if 8.5 < dat(i,1) && 8.7 > dat(i,1)
a = [a;dat(i,2)];
elseif 12.5 < dat(i,1) && 12.6 > dat(i,1)
b = [b;dat(i,2)];
elseif 13.2 < dat(i,1) && 13.4 > dat(i,1)
c = [c;dat(i,2)];
elseif 14.5 < dat(i,1) && 14.6 > dat(i,1)
d = [d;dat(i,2)];
end
end