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

조회 수: 6 (최근 30일)
Nishant Singhal 2017년 4월 19일
댓글: Stephen23 2017년 4월 19일
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
##### 댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
Stephen23 2017년 4월 19일

댓글을 달려면 로그인하십시오.

### 답변 (1개)

Thorsten 2017년 4월 19일
편집: Thorsten 2017년 4월 19일
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;

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

### 태그

아직 태그를 입력하지 않았습니다.

### Community Treasure Hunt

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

Start Hunting!

Translated by