How do I apply an index to many different variables at once?
I have several vectors of different data types, all the same sizes. In particular, I have Datetimes as datestamps for pairs, strings, etc. I want to quickly and easily delete all weekend so that I create and index the data. How do I apply this index to all my variables?
Currently I have (for a small subset),
Date=Date(idx); Meter=Meter(idx); Model=Model(idx); . . .
Is there some existing function like
[Date,Meter,Model,...]=fnc(idx,Date,Meter,Model,...);
I was tempted to write my own, should be very simple, but didn't feel like it if there was another simple or effective alternative.
source to share
You could like this:
t = cellfun(@(x) x(idx), {Date, Meter, Model}, 'uniformoutput', 0);
[Date, Meter, Model] = deal(t{:});
In recent versions of Matlab, you can skipdeal
and thus the second line will look like this:
[Date, Meter, Model] = t{:};
It would be easier if, instead of separate variables, you had an array of cells, so that each cell contained one of your variables. In this case, you simply use
myCell = cellfun(@(x) x(idx), myCell, 'uniformoutput', 0);
source to share
An alternative to using cell fun as pointed out by @Luis Mendo is to use structfun
- this way you keep the variable names for each array.
You need to have an al variable in the structure for this to work:
myStruct.Date = Data;
myStruct.Meter = Meter;
myStruct.Model = Model;
subStruct = structfun ( @(x) x(idx), myStruct, 'UniformOutput', false )
source to share