Can I modify values in a vector within a for loop for a recursive function?
1 次查看(过去 30 天)
显示 更早的评论
I have a recursive function that uses n, n-1, and n-2. I need to create a function that will return a vector or array of size 1x100, containing those function values. (Please help me figure out data type). It will take two initial values to start the function, and then return the array/vector.
If I create an array with zeros(1,100) at command line, set array(1) and array(2) with the initial values, and try to get it run on that, it at least generates some numbers. When I try this loop at command line with the same array, all the elements go either NaN or 0 >1E130.
I keep getting errors when I try modifying the array within the for loop. I don't understand how (better) to do this; I think I'm messing up the index accessing within the for loop.
Also, I'm not sure how to specify WHAT is being returned.
function [f] = recurs(a,b)
vectortobereturned=zeros(1,100);
index=100;
recursionstartoffset=3
vectortobereturned(1)=a;
vectortobereturned(2)=b;
for i=recursionstartoffset:index
iminusone=vectortobereturned(i-1);
iminustwo=vectortobereturned(i-2);
icurrent=0.01*iminusone^2-1.75*iminusone+4;
vectortobereturned(i)=icurrent;
end
return vectortobereturned
3 个评论
Walter Roberson
2018-6-6
This is not recursive. For it be recursive, function recurs would have to make a call to function recurs .
Stephen23
2018-6-6
"I have a recursive function ..."
No recursion is shown in the question. A loop does not mean recursion.
" When I try this loop at command line with the same array, all the elements go either NaN or 0 >1E130."
I guess either you have a bug, or perhaps this is the correct behavior. We don't know either because your code contains no comments or explanation what it should be doing.
"Also, I'm not sure how to specify WHAT is being returned."
Hint: you define f to be the function output. But inside the function, where is f defined?
回答(1 个)
Varun Garg
2018-6-6
I think you are not clear about the syntax of
function
A sample snippet :
function y=printNumbers(x)
for i=1:10
y(i)=i;
end
end
Notice here that in the first line y was set equal to the function name. So by default when the function ends, y is the value (here, vector) which will be returned. No need to explicitly use return statement which might probably give you errors too.
Also, you say that you are trying to implement a recursive function. A general notion of recursive function is that when a function calls itself. A very basic example would be:
function y=fact(x)
if x>1
y=fact(x-1)*x;
else
y=1;
end
In your code I can't see recurs being called inside anywhere.
So I would suggest you to read about recursive functions first. There are a lot good resources available on the internet.
Hope it helps.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!