Search code examples
matlabfor-loopindexingtimeincrement

MATLAB Loop with non-integer Increments and Starting at Index Zero


I have the following loop:

t_train = 25;
t_wash = 5;

for t = 1:t_train
    if t > t_wash
        X(:,t-t_wash) = L(:,t-t_wash);
    end
end

I would like to change the loop to the following:

t_train = 25;
t_wash = 5;
dt = (10^-1);

for t = 0:dt:t_train
    if t > t_wash
        X(:,t-t_wash) = L(:,t-t_wash);
    end
end

This does not work since I am using a non-integer increment and starting at index 0. Is there a way to do both of these things in MATLAB?


Solution

  • separate between the information your vector contains (in this case time), and the fact that it is a vector of some length. For example, you can define any time vector :

    t=0:dt:t_max;
    

    and loop over its number of elements given by numel(t):

    for n=1:numel(t)
        if t(n)>t_wash
            X(n) = t(n)-t_wash;
        end
    end
    

    of course, Matlab can do so much more, such that a for loop is not needed, for example, the statement t>t_wash yields a logical vector of 0's and 1's and so you can write X(t>t_wash)=L(t>t_wash) to assign the values of L into X in one line...