Brian
Brian

Reputation: 27392

Unexplained extra entry in array

In a tutorial I was running today, the following problem came up a few times.

The code was something like this

x = [ x0 + v*cosd(theta) * t, y0 + v*sind(theta) * t + .5 *g * t^2]

However, when you output x, it had 3 entries with a zero before the two calculated values. I have no idea how that happened. I restyled the same code exactly and this problem disappeared. Could this be some sort of bug with MATLAB?

Upvotes: 0

Views: 57

Answers (1)

slayton
slayton

Reputation: 20319

In matlab if you combine a vector with a scalar the resulting value is a vector. For example:

a = 1;
b = [1, 2];
c = a+b; % returns [2, 3];

So lets break down your equation:

 x = [ x0 + v*cosd(theta) * t, y0 + v*sind(theta) * t + .5 *g * t^2]

into:

A = x0 + v*cosd(theta) * t;
B = y0 + v*sind(theta) * t + .5 *g * t^2;
x = [ A, B];

A and B must both be scalars for x to be 1x2. Your result is 1x3 because one of your variables because either A or B is 1x2. This is the result of x0, v, theta, t, y0, or g not being a scalar but a 1x2 vector.

My suspicion is that g, x0, or y0, is the culprit as these variables are unique to a single equation. So I'd start by checking the size of these values. However without knowing the values of your variables I can't be sure.

Upvotes: 2

Related Questions