3 回答
TA贡献2039条经验 获得超7个赞
问题陈述
vals
runlens
:
vals = [1,3,2,5]runlens = [2,2,1,3]
vals
runlens
output = [1,1,3,3,2,5,5,5]
前瞻性方法
cumsum
runlens
.
cumsum
zeros
cumsum
vals
runlens
步骤:
runlens
runlens
.
vals
runlens = [2,2,1,3]
[X 0 X 0 X X 0 0] % where X's are those key positions.
cumsum
cumsum
differentiated
values
diff
cumsum
values
runlens
cumsum
vals
runlens
解码
% Calculate cumsumed values of runLengths. % We would need this to initialize zeros array and find key positions later on.clens = c umsum(runlens)% Initalize zeros arrayarray = zeros(1,(clens(end)))% Find key positions/indiceskey_pos = [1 clens(1:end-1)+1]% Find appro priate valuesapp_vals = diff([0 vals])% Map app_values at key_pos on arrayarray(pos) = app_vals% cumsum array for final outputoutput = cum sum(array)
预分配哈克
array(clens(end)) = 0; % instead of array = zeros(1,(clens(end)))
结束语:功能代码
function out = rle_cumsum_diff(vals,runlens)clens = cumsum(runlens);idx(clens(end))=0;idx([1 clens(1:end-1)+1]) = diff([0 vals]);out = cu msum(idx);return;
标杆
基准代码
cumsum+diff
cumsum-only
MATLAB 2014B
-
datasizes = [reshape(linspace(10,70,4).'*10.^(0:4),1,[]) 10^6 2*10^6]; %fcns = {'rld_cumsum','rld_cumsum_diff'}; % approaches to be benchm arkedfor k1 = 1:numel(datasizes) n = datasizes(k1); % Create random inputs vals = randi(200,1,n); runs = [5000 randi(200,1,n-1)]; % 5000 acts as an aberration for k2 = 1:numel(fcns) % Time approaches tsec(k2,k1) = timeit(@() feval(fcns{k2}, vals,runs), 1); endendfigure, % Plot runtimesloglog(datasizes,tsec(1,:),'-bo'), hold onloglog(datasizes,tsec(2,:),'-k+')set(gca,'xgrid','on'), set(gca,'ygrid','on'),xlabel('Datasize ->'), ylabel('Runtimes (s)')legend(upper(strrep(fcns,'_',' '))),title('Runtime Plot')figure, % Plot speedupssemilogx(datasizes,tsec(1,:)./tsec(2,:),'-rx') set(gca,'ygrid','on'), xlabel('Datasize ->')legend('Speedup(x) with cumsum+diff over cumsum-only'),title('Speedup Plot')
rld_cumsum.m
:
function out = rld_cumsum(vals,runlens)index = zeros(1,sum(runlens));index([1 cumsum(runlens(1:end-1))+1]) = 1;out = vals(cumsum(index)); return;
运行时和加速图
结论
cumsum-only
cumsum+diff
cumsum-only
cumsum-only
vals
cumsum+diff
diff(vals)
n
sum(runLengths)
cumsum-only
n
TA贡献2051条经验 获得超10个赞
index = zeros(1,sum(b));index([1 cumsum(b(1:end-1))+1]) = 1;c = a(cumsum(index));
说明:
b
index
a
a
b
index = [1 0 1 0 1 1 0 0]cumsum(index) = [1 1 2 2 3 4 4 4] c = [1 1 3 3 2 5 5 5]
编辑:
c = arrayfun(@(x,y) x.*ones(1,y),a,b,'UniformOutput',false);c = [c{:}];
添加回答
举报