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.

+3


source to share


3 answers


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);

      

+3


source


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 )

      

+4


source


You can define this function as an anonymous function like this:

f=@(idx, varargin) subsref(cellfun(@(x) x(idx), varargin, 'uni', 0), substruct('{}', {':'}));

      

Now

>> A=rand(1,3)
A =
    0.9649    0.1576    0.9706
>> B={'a' 'b' 'c'}
B = 
    'a'    'b'    'c'
>> [x,y]=f(2,A,B)
x =
    0.1576
y = 
    'b'

      

+1


source







All Articles