於是,我就在你的代碼提高一點點,你可以看到下面的結果:
%% My approach to solve the question (it has a slightly better runtime)
function c = myapproach(a, cells)
c = {a.b};
sz = [a.Size];
for i = 1:cells
c{i} = c{i}(1:sz(i));
end
end
雖然這不會避免for循環,它有一個稍微好一點的運行時間。我得到的運行時間(在單元= 50000)是:@yourapproach = 0.0889, @myapproach = 0.0721, @rahnema1 = 0.2329
以下是我用來解決這個問題的代碼。我也對一些代碼的改進用來生成a
(通過註釋標記)
function solveit()
cells = 50000;
maxVal = 40;
Sizes = randi(maxVal, 1, cells);
a(cells) = struct('Size', 0, 'b', []); %% Improved by preallocating a
for i = 1:cells
a(i).b = rand(1, maxVal); %% Improved by removing the unnecessary double loop
a(i).Size = Sizes(i);
end
fun1 = @() yourapproach(a, cells);
fun2 = @() myapproach(a, cells);
fun3 = @() rahnema1(a);
%% Show runtimes
timeit(fun1)
timeit(fun2)
timeit(fun3)
c1 = fun1();
c2 = fun2();
c3 = fun3();
%%Show approach equivalence
disp(isequal(c1, c2))
disp(isequal(c1, c3))
end
%% Your approach
function c = yourapproach(a, cells)
c = cell(1, cells);
for i = 1:cells
sz = a(i).Size;
c{1,i} = a(i).b(1:sz);
end
end
%% Approach mentioned by rahnema1
function c = rahnema1(a)
cc = struct2cell(a);
sz = [cc{1:2:end}];
sz = [sz;40-sz];
dat = [cc{2:2:end}];
c = mat2cell(dat, 1, sz(:));
c = c(1:2:end);
end
編輯:我加入arrayfun
方法,但它比for
環
function c = newapproach(a)
sz = [a.Size];
c = arrayfun(@(x, y) x.b(1:y), a, sz, 'UniformOutput', false);
end
慢至少10倍
目前的解決方案有什麼問題? – excaza
當前的解決方案使用了一個for循環,我想避免這個循環,因爲'cells'通常在50000左右。 – evolved
快速解決方案可能是創建一個mex文件。 – m7913d