# Indexing into timetables with an array of logicals

6 views (last 30 days)
Rob on 6 Apr 2020
Answered: Ameer Hamza on 6 Apr 2020
Hi,
Is it possible to index into a timetable (or table) with an array of logicals for the purpose of assigning, say, NaNs wherever an element of the array is TRUE?
Here's a simple example:
% Create a timetable:
dates = datetime([2010 1 1;
2011 1 1;
2012 1 1;
2013 1 1;
2014 1 1]);
data = array2timetable(rand(5, 3), 'RowTimes', dates);
% Find where the values are less than 0.5:
idx = data{:, :} < 0.5;
% How do I directly replace the values in 'data' indexed by 'idx' with NaNs?
% For example, I thought this might work, but it doesn't: data{idx} = NaN;
% It appears I'm unable to do so without doing something a bit convoluted like this:
tmp = data{:, :};
tmp(idx) = NaN;
data{:, :} = tmp;

madhan ravi on 6 Apr 2020
Edited: madhan ravi on 6 Apr 2020
It’s the simplest way you can do it.

Ameer Hamza on 6 Apr 2020
The easiest way might be to convert the timetable to an array, convert values to nan based on the condition and recreate the timetable. However, the following show an example of how to do it directly
% Create a timetable:
dates = datetime([2010 1 1;
2011 1 1;
2012 1 1;
2013 1 1;
2014 1 1]);
data = array2timetable(rand(5, 3), 'RowTimes', dates);
% Find where the values are less than 0.5:
idx = data{:, :} < 0.5;
x = [0 nan];
data.Variables = data.Variables.*~idx + x(idx+1)