MATLAB Answers

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

9 views (last 30 days)
gtstudent on 6 Jun 2018
Answered: 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)
for i=recursionstartoffset:index
return vectortobereturned


Walter Roberson
Walter Roberson on 6 Jun 2018
This is not recursive. For it be recursive, function recurs would have to make a call to function recurs .
Stephen Cobeldick
Stephen Cobeldick on 6 Jun 2018
"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.

Answers (1)

Varun Garg
Varun Garg on 6 Jun 2018
I think you are not clear about the syntax of
A sample snippet :
function y=printNumbers(x)
for i=1:10
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
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.


Sign in to comment.

Sign in to answer this question.

Translated by