MATLAB Answers

0

Can I modify values in a vector within a for loop for a recursive function?

Asked by gtstudent on 6 Jun 2018
Latest activity Answered by Varun Garg on 6 Jun 2018
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 Comments

This is not recursive. For it be recursive, function recurs would have to make a call to function recurs .
"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?

Sign in to comment.

1 Answer

Answer by Varun Garg on 6 Jun 2018

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.
And also read the documentation of function here.
Hope it helps.

  0 Comments

Sign in to comment.