# How to pass a variable input into a function in matlab?

1. Jul 25, 2012

### supernova1387

I have an ode function which is of the form:

function [output]=Fun[input1,input2,input3]

which is solving a set of non-linear differential equations. input1 and 3 are fixed but input2 is a variable. Say:

input1=3; % a constant
input3=20;
input2=[2 4 6 8];

function Fun is being called in an m.file called main. The ode is being solved 20 times (input3 defines number of repetition). I want Fun to use a different element of vector input2 each time and repeat this process again and again until the number of input3. That is:

first time solving : input2=2;
second time solving: input2=4;
.
.
.
fifth time solving: input5=2 again

and this process must repeat until Fun reaches input3=20

Any suggestions are welcome.

2. Jul 25, 2012

### chiro

Hey supernova1387.

This seems like a simple function with a loop and a function call inside of it.

Can you show us any code you have currently? Do you know how to use loops and how to use the counters in the loops for passing to other functions as arguments?

3. Jul 26, 2012

### supernova1387

The code is quite long and complicated. I can give you a simpler example. Imagine we want to simulate a bouncing ball where input3 defines number of bounces. We have equations of motion, impact phase and event. The event occurs when y=0(the ball contacts the ground). Now what I want to do is to change this event for each bounce. Lets say I have 20 bounces but my ground is moving up and down too so the event occurs at y=0.5, 0.1 ,0 etc rather than always at y=0. In other words, y is a vector rather than a single number. Lets say:
y=[0.5, 0.1, 0, -0.1, 0.1, -0.5]

It is kind of like a rough surface where y defines the height of the roughness and the ball contacts the floor when the height of the ball is equal to the elements of y-matrix at each bounce. The y-matrix has just 6 elements but it will repeat itself. That is after the 6th bounce, y would be y=0.5 again.

I just consider motion is y-direction and assume the ball will just bounce up and down. Any suggestions?

4. Jul 26, 2012

### chiro

Well you can construct a simple loop within a loop to do this. Basically if you have 20 bounces but a vector with 5 entries, the outer most loop does 20/5 = 4 iterations and the inner loop does 5 iterations (or the size of your vector).

If you want to re-use inputs or do periodic calculations like the one above: you can either use another loop or use the modulus function. Using the modulus function for i = 0 to 19 mod 5 would give 0,1,2,3,4,0,1,2,3,4 and so on and you can use this as an index.