【发布时间】:2016-11-07 03:55:21
【问题描述】:
我正在开发一个用面向对象的 Matlab (2016a) 编写的项目,我目前正在尝试优化一些代码以改善运行时。使用分析器,我发现了一种可能的性能改进——我们大量使用了一个函数,它的实现似乎效率特别低,而且不是特别“matlab”。
本质上,我想知道是否有一种有效的方法可以索引到类对象的 CellArray 以仅提取具有我们感兴趣的特定属性值的对象。目前我们使用 for 循环来执行此操作我想知道我是否可以做一些事情来矢量化它,或者可能使用某种逻辑索引。不幸的是,我的搜索似乎没有找到答案,使用对象对 CellArrays 进行逻辑索引似乎不是很多人想做的事情......
这是我正在尝试改进的功能的最小工作示例。 MWE 的其他代码如下。
我知道通过更改实现的其余部分来完全避免必须这样做来解决此问题可能更明智。但是,如果可能的话,我宁愿避免这样做。
编辑:在我的典型用例中,单元格对象的数量很少(大约 10 或 20 个),但效率低下的方法被调用了很多(数千次)。这么小的数组,很多查找操作。
%% is there a "more matlab" / faster way to do this?
function outputCellArray = ThereMustBeABetterWayToDoThis(cellArrayOfClassObjects,arrayOfTypesToFind)
outputCellArray = {};
for iType = 1:numel(arrayOfTypesToFind)
thisType = arrayOfTypesToFind(iType); % this line is the real bottleneck according to the profiler
for iObject = 1:numel(cellArrayOfClassObjects)
thisClassObj = cellArrayOfClassObjects{iObject};
if (thisClassObj.specificEnumType == thisType) % this line is also quite slow
outputCellArray{end+1} = thisClassObj;
end
end
end
类定义:
classdef MyClass < handle %% dummy example class
properties
specificEnumType;
x;
y;
end
methods
function this = MyClass(x,y,specificEnumType)
this.specificEnumType = specificEnumType;
this.x = x;
this.y = y;
end
end
end
还有一个:
classdef EnumType < uint32 %%dummy example class
enumeration
Type0 (0),
Type1 (1),
Type2 (2),
Type3 (3)
end
end
调用整个事物的脚本:
% use this script to call the whole thing
%% we have a cell array of class objects: they each have different enumTypes as a property
cellArrayOfClassObjects{1} = MyClass(rand,rand,EnumType.Type0);
cellArrayOfClassObjects{2} = MyClass(rand,rand,EnumType.Type1);
cellArrayOfClassObjects{3} = MyClass(rand,rand,EnumType.Type2);
cellArrayOfClassObjects{4} = MyClass(rand,rand,EnumType.Type3);
cellArrayOfClassObjects{5} = MyClass(rand,rand,EnumType.Type3);
cellArrayOfClassObjects{6} = MyClass(rand,rand,EnumType.Type2);
%% we want to find the ones that have these specific enumTypes
arrayOfTypesToFind = [EnumType.Type0,EnumType.Type2];
%% there must be a better way than this inefficient method
outputArray = ThereMustBeABetterWayToDoThis(cellArrayOfClassObjects,arrayOfTypesToFind);
【问题讨论】:
标签: performance matlab oop indexing cell-array