我喜歡使用cellfun對於繪製操作,而不是循環,例如,如果我擁有多套傳感器數據,每個組都有多個列(因爲每套多個傳感器),它使用
numOfSensors = 5;
numOfSets = 6;
%% sample data preparation
x = 1:100;
y = rand(length(x), numOfSets*numOfSensors);
yCell = mat2cell(y, 100, numOfSensors*ones(1,numOfSets)); % this is my sensor data
scaleCell = num2cell(fliplr(cumsum(1:numOfSets)));
yCell = cellfun(@(x, scale)x.*scale, yCell, scaleCell, 'unif', false);
%% plot preparation
nameCell = arrayfun(@(x)['sensor set ' num2str(x)], 1:numOfSets, 'unif', false);
colorCell = num2cell(lines(numOfSets), 2)';
%% plot
figure, hold all,
set(gca, 'ColorOrder', [0 0 0], 'LineStyleOrder', {'-','--','-*','-.',':'})
h = cellfun(@(y, name, c)plot(x, y, 'linewidth', 1.5, 'displayName', name, 'color', c), yCell, nameCell, colorCell, 'unif', false);
hh = cellfun(@(x)x(1), h, 'unif', false);
legend([hh{:}])
是非常方便而不是循環。此示例繪製所有數據集,每個數據集都以其自己的顏色繪製,每個數據集使用其他線型繪製。圖例只顯示每個數據集(注意:這也可以通過使用hggroups來完成)。
或者更簡單的使用情況 - 我再次有數據的單元陣列,並希望有在一個簡短的看法:
figure, hold all, cellfun(@plot,dataCell)
就是這樣,一條線,速度非常快,在命令行。另一個很好的用例是使用mean(),max(),min(),std()等壓縮高維數據數值數據,但你已經提到了這一點。如果數據的大小不統一,這變得更加重要。
相關問題: http://stackoverflow.com/questions/16143314/matlab-arrayfun-cellfun-spfun-and-structfun-vs-simple-for-loop – Shai