Search code examples
matlabmatlab-figure

What does x(1) mean in matlab?


I'm really new to matlab and I need some help, I know java and python. Here's a code I want to understand

x(1) = 0
y(1) = 0

i = 1
x(i+1)=x(i)+vx*t+.5*a*t^2;
i=i+1;

end

I want to know what is happening here, "vx", "t" and "a" are variables tho


Solution

  • x(1) = 0 and y(1) = 0 is very similar to initializing a list / array in Python where x and y are the list variables and the first position is 1. MATLAB starts indexing at 1, and not 0 like in Java and Python. The similar syntax in Java or Python is: x[0] = 0; y[0] = 0. MATLAB uses round braces to index into an array / vector / list.

    i = 1
    x(i+1)=x(i)+vx*t+.5*a*t^2;
    i=i+1;
    

    This is pretty simple. i is some sort of loop variable or index variable... which you failed to show us that this code is probably part of a loop. The code just sets the next value of x or the second element in the array or list to x(i) + vx*t + 0.5*a*t^2. The * operator is multiplication and the ^ is the exponentiation operator. In Python, this is equivalent to saying x[i] + vx*t + 0.5*a*(t**2). Now the origin of this equation actually comes from calculating the displacement of a body mass using Newtonian physics - the Kinematic Equations actually. As such vx is the velocity of the body mass and a is the acceleration. t would be the time point you are considering. Specifically, the displacement can be calculated as follows:

    Source: The Physics Classroom - Kinematic Equations

    Look at the top left equation as that is what the statement is doing in the code. This only calculates the displacement at one point in time. Therefore, what you are doing is adding the displacement that this body mass encounters at some fixed point t a certain amount of times. x captures the total displacement overall from the beginning to end. The next statement after is just incrementing the loop counter. The thing about MATLAB is that you can dynamically extend the length of a list / array / vector whereas Python or Java will give you an out-of-bounds error. However, it's recommended you should pre-allocate the right amount of memory to use before using it for efficiency. See this informative post for more details: Efficient Array Preallocation in MATLAB.