我有几个不同数据类型的向量,它们的大小都相同。具体来说,我有Datetimes作为双精度,字符串等的日期戳。我希望快速轻松地删除所有的周末,所以我从日期时间创建和索引。我现在如何将这个索引应用到所有变量上?
目前我有(对于一个小子集),
Date=Date(idx);
Meter=Meter(idx);
Model=Model(idx);
.
.
.
是否有一些已经存在的函数,例如,
[Date,Meter,Model,...]=fnc(idx,Date,Meter,Model,...);
我一直想写我自己的,应该很容易,但不想如果有其他简单或有效的替代。
如@Luis Mendo所指出的,使用cell fun的另一种选择是使用structfun
-这样您可以为每个数组保留变量名称。
你需要把所有的变量放在一个结构中,这样才能正常工作:
myStruct.Date = Data;
myStruct.Meter = Meter;
myStruct.Model = Model;
subStruct = structfun ( @(x) x(idx), myStruct, 'UniformOutput', false )
你可以这样做:
t = cellfun(@(x) x(idx), {Date, Meter, Model}, 'uniformoutput', 0);
[Date, Meter, Model] = deal(t{:});
在最近的Matlab版本中,您可以省略deal
,因此第二行变为:
[Date, Meter, Model] = t{:};
如果不是单独的变量,而是一个单元格数组,这样每个单元格包含一个变量,这将更容易。在这种情况下,你只需使用
myCell = cellfun(@(x) x(idx), myCell, 'uniformoutput', 0);
您可以将该函数定义为如下的匿名函数:
f=@(idx, varargin) subsref(cellfun(@(x) x(idx), varargin, 'uni', 0), substruct('{}', {':'}));
现在>> 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'