How can I repeatedly put a function result into itself, and get a matrix of the results?

9 views (last 30 days)
I want to take the output of a function and put it back into the function to get my next output, then get a matrix of all the results. For example, if my function was b=3*a+1, I would want to get the matrix [4, 13, 40, 121...] etc, but a very large size, eg. 500 numbers.
Here's how I'm currently doing it. I have the function:
function [ y ] = test( x )
%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here
y=3*x+1
assignin('base', 'B', evalin('base', 'B')+1)
end
The purpose of the assignin bit is to increase B (a variable in my main workspace) by 1 every time I use the function.
I start by setting B as 0. Then in my command window I do:
M(1,B)=test(1)
This sets M as 4.
Then I do:
M(1,B)=test(M(1,B))
This makes M a 1x2 matrix [4, 13].
I have to keep repeating this last command to get more values in matrix M.
Is there a way I could get, let's say, 500 values of M all at once, giving me a 1x500 matrix in one go?
P.S. 3X+1 is just an example - the equation I'm actually using is a bit more complicated, so finding a general equation for the nth term won't help.
I'm on 2016a

Answers (1)

Thorsten
Thorsten on 19 Apr 2017
Edited: Thorsten on 19 Apr 2017
N = 500;
Y = zeros(1, N); % preallocate for speed
Y(1) = myfun(1);
for i = 2:N
Y(i) = myfun(Y(i-1);
end
with myfun.m defined as
function y = myfun(x) % use a name for the function that is not a Matlab command
y = 3*x+1;

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

No tags entered yet.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!