Problem with function @(t) [ (1/2)*a*t.^2]

2 vues (au cours des 30 derniers jours)
Douglas Alves
Douglas Alves le 26 Mai 2014
Commenté : Star Strider le 26 Mai 2014
function eulers_for_mv
a = .5 ;
t = linspace(0,2) ;
dt = t(2) - t(1) ;
x = zeros(1,length(t));
v = zeros(1,length(t));
for i=1:length(t)-1
v(i+1) = v(i) + dt*a
x(i+1) = x(i) + dt*v(i) ;
end
original_eq = @(t) [x(1) + v(1)*t +(1/2)*a*t.^2] ;
original_eq(t) ---> returns to me a 1x200 matrix because I left some room between t and 1/2 it shouldnt matter no?? if I take this away writing ...t+(1/2) ... it`ll give me the correct 1x100 matrix. why??

Réponse acceptée

Star Strider
Star Strider le 26 Mai 2014
MATLAB interprets spaces in matrices as separators, so it does matter in that situation. In matrices, put parentheses around expressions you want MATLAB to consider as single expressions.
If you want ‘v(1)*t +(1/2)*a*t.^2’ to be a single expression, write it as:
original_eq = @(t) [x(1) + (v(1)*t +(1/2)*a*t.^2)] ;
  4 commentaires
Douglas Alves
Douglas Alves le 26 Mai 2014
I understand it perfectly. Thanks a lot!!
Star Strider
Star Strider le 26 Mai 2014
When I run:
z = original_eq(t);
fznz = find(z ~= 0);
after the other elements of your code (I didn’t create a function file for it), the first 101 elements of ‘z’ (a (1x200) vector) are all zero. Only the last 99 are non-zero.
Note that x(1) and v(1) are both zero and do not change. It is adding x(1) to v(1)*t, because otherwise I would expect the vector to be 201 elements long. Because t(1)=0, the first term of (1/2)*a*t.^2 would also be zero, accounting for the first 101 elements all being zero. So it is concatenating the elements v(1)*t, and (1/2)*a*t.^2 as separate elements of a single vector, creating your (1x200) element vector.
In this example, note the difference between:
t = 1:5;
qq = @(t) [0 + t +t.^2];
w = qq(t)
and:
t = 1:5;
qq = @(t) [0 + t + t.^2];
w = qq(t)
So the spaces (or lack of them) matter in how MATLAB interprets the vector calculation. In the first one, the ‘+’ before t.^2 does nothing (although a minus sign would produce the negative of t.^2) because MATLAB is not interpreting it as an arithemtic operator, while in the second, MATLAB interprets all the spaces and the operators as signifying a single expression.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Elementary Math dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by