[英]vectorizing function in octave / matlab
I have a function that I was wondering if it was possible to vectorize it and not have to use a for loop. 我有一个我想知道是否可以对其向量化的函数,而不必使用for循环。 The code is below. 代码如下。
a=1:2:8
for jj=1:length(a)
b(jj)=rtfib(a(jj)); %fibbonacci function
end
b
output below: 输出如下:
a =
1 3 5 7
>>>b =
1 3 8 21
I was trying to do it this way 我试图这样做
t = 0:.01:10;
y = sin(t);
but doing the code below doesn't work any suggestions? 但是执行下面的代码没有任何建议吗? ps: I'm trying to keep the function rtfib because of it's speed and I need to use very large Fibonacci numbers. ps:由于速度太快,我试图保留rtfib函数,我需要使用非常大的斐波那契数。 I'm using octave 3.8.1 我正在使用八度3.8.1
a=1:2:8
b=rtfib(a)
Here's the rtfib code below as requested 这是要求的以下rtfib代码
function f = rtfib(n)
if (n == 0)
f = 0;
elseif (n==1)
f=1;
elseif (n == 2)
f = 2;
else
fOld = 2;
fOlder = 1;
for i = 3 : n
f = fOld + fOlder;
fOlder = fOld;
fOld = f;
end
end
end
You can see that your function rtfib
actually computes every Fibonacci number up to n
. 您可以看到您的函数rtfib
实际上计算了每个斐波那契数,直到n
为止。 You can modify it so that is stores and returns all these number, so that you only have to call the function once with the maximum number you need: 您可以对其进行修改,以便存储并返回所有这些数字,因此您只需以所需的最大数字调用一次函数:
function f = rtfib(n)
f=zeros(1,n+1);
if (n >= 0)
f(1) = 0;
end
if (n>=1)
f(2)=1;
end
if (n >= 2)
f(3) = 2;
end
if n>2
fOld = 2;
fOlder = 1;
for i = 3 : n
f(i+1) = fOld + fOlder;
fOlder = fOld;
fOld = f(i+1);
end
end
end
(It will return fibonnaci(n) in f(n+1), if you don't need the 0 you could change it so that it returns fibonnaci(n) in f(n) if you prefer) (它将在f(n + 1)中返回fibonnaci(n),如果您不需要0,则可以对其进行更改,以便您更喜欢在f(n)中返回fibonnaci(n)。)
Then you only need to call 那你只需要打电话
>>f=rtfib(max(a));
>>b=f(a+1)
b =
1 3 8 21
If you don't want to store everything you could modify the function rtfib
a little more, so that it takes the the array a
as input, compute the Fibonacci numbers up to max(a)
but only stores the one needed, and it would directly return b
. 如果您不想存储所有内容,则可以多修改一点rtfib
函数,以便将数组a
作为输入,计算最大为max(a)
的斐波那契数,但只存储所需的那个直接返回b
。 Both solutions will slow down rtfib
itself but it will be a lot faster than calculating the Fibonacci numbers from 0 each time. 这两种解决方案都会减慢rtfib
本身的速度,但比每次从0计算斐波那契数都要快得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.