MATLAB:从for循环转换为无循环

时间:2014-10-05 20:38:11

标签: matlab loops

我有一个由教师提供的功能,我们无法看到内部工作原理。

此功能基本上集成了您输入的内容。

这是我们的循环:

for i = 1:length(time)-1
    intdefValues(i) = intdef(t, r, time(i), time(i+1));
end

我们正在尝试这样做:

intdefValues = intdef(t, r, time(1:end-1), time(2:end));

我们错了吗?无论如何,该功能是否支持向量?

如果你好奇的话,该函数的语法;

intdef(t, x, a, b)

其中t =时间向量,x =函数,a,b是开始/结束参数。

1 个答案:

答案 0 :(得分:-1)

tic();                               % ------------
                                     % TEST ALSO
                                     % PERFORMANCE:

                                     % prepare another "vectorOfTimeENDs",
                                     % aligned with your loop-ing strategy
                                     % for a fully  vectorised call

startsVector = time(1:end-1);        % just a syntax-sugar, may omit for speed == time(1:end-1)
  endsVector = time(2:end);          % this one is important

intdefValues = intdef( tVector, rFunction, startsVector, endsVector );
toc()

% ---------------------------------------------------------------------------
tic();                               % COMPARE WITH THE ORIGINAL FOR/LOOP:
for i = 1:length(time)-1
    intdefValues(i) = intdef( tVector, rFunction, time(i), time(i+1) );
end
toc()