问题描述
给出一个像a = [ -1; 0; 1];
这样的数组.对于每个a(i)
,我需要使用linspace(min(a(i),0),max(a(i),0),3);
计算线性间隔的矢量,其中每个linspace-vector都应存储在矩阵中:
Given an array like a = [ -1; 0; 1];
. For each a(i)
, I need to compute a linearly spaced vector with linspace(min(a(i),0),max(a(i),0),3);
, where each linspace-vector should be stored into a matrix:
A = [-1 -0.5 0;
0 0 0;
0 0.5 1];
通过for循环,我可以这样做:
With a for loop, I can do this like so:
for i=1:3
A(i) = linspace(min(a(i),0),max(a(i),0),3);
end
如何在不使用循环的情况下实现这一目标?
How can I achieve this without using loops?
推荐答案
我能想到的最快方法是计算步长,并使用隐式二进制扩展从中构造向量.
The fastest way I can think of is calculating the step-size, construct the vector from that using implicit binary expansion.
a = [ -1; 0; 1];
n = 3;
stepsizes = (max(a,0)-min(a,0))/(n-1);
A = min(a,0) + (0:(n-1)).*stepsizes;
时间:
使用timeit(@SO)
的几个结果(使用timeit(@SO)
并从要计时的块中删除注释):
A couple of timeit
results using (use timeit(@SO)
and remove comments from the blocks to be timed):
function SO()
n = 1e3;
m = 1e5;
a = randi(9,m,1)-4;
% %Wolfie
% aminmax = [min(a, 0), max(a,0)]';
% A = interp1( [0,1], aminmax, linspace(0,1,n) )';
% %Nicky
% stepsizes = (max(a,0)-min(a,0))/(n-1);
% A = min(a,0) + (0:(n-1)).*stepsizes;
% %Loop
% A = zeros(m,n);
% for i=1:m
% A(i,:) = linspace(min(a(i),0),max(a(i),0),n);
% end
%Arrayfun:
A = cell2mat(arrayfun(@(x) linspace(min(x,0),max(x,0),n),a,'UniformOutput',false));
那么时间是:
- 狼:2.2243秒
- 矿山:0.3643秒
- 标准循环:1.0953 s
-
arrayfun
:2.6298 s
- Wolfie: 2.2243 s
- Mine: 0.3643 s
- Standard loop: 1.0953 s
arrayfun
: 2.6298 s
这篇关于Linspace应用于数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!