代码
Q = mat2cell(num2cell([a b]),ones(1,numel(a)),2)
例子
带输入输出显示的代码
a = [2; 3; 4]; %// Inputs
b = [1; 5; 8];
Q = mat2cell(num2cell([a b]),ones(1,numel(a)),2); %// Output
celldisp(Q) %// Display results
代码运行时的输出
Q{1}{1} =
2
Q{1}{2} =
1
Q{2}{1} =
3
Q{2}{2} =
5
Q{3}{1} =
4
Q{3}{2} =
8
基准测试
循环方法的函数
function out = loop1(a,b)
out = cell(size(a,1),1);
for i=1:size(out,1)
out{i}{1}=a(i,:);
out{i}{2}=b(i,:);
end
return;
矢量化方法的功能
function out = vec1(a,b)
out = mat2cell(num2cell([a b]),ones(1,numel(a)),2);
return;
基准代码
N_arr = [50 100 200 500 1000 2000 5000 10000 50000]; %// array elements for N
timeall = zeros(2,numel(N_arr));
for k1 = 1:numel(N_arr)
N = N_arr(k1);
a = randi(9,N,1);
b = randi(9,N,1);
f = @() loop1(a,b);
timeall(1,k1) = timeit(f);
clear f
f = @() vec1(a,b);
timeall(2,k1) = timeit(f);
clear f
end
%// Graphical display of benchmark results
figure,
hold on
plot(N_arr,timeall(1,:),'-ro')
plot(N_arr,timeall(2,:),'-kx')
legend('Loop Method','Vectorized Method')
xlabel('Datasize (N) ->'),ylabel('Time(sec) ->')
结果
结论
看起来矢量化方法是要走的路,因为与各种数据大小的循环方法相比,它的性能(在运行时方面)几乎翻了一番。