필터 지우기
필터 지우기

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

조회 수: 3 (최근 30일)
Douglas Alves
Douglas Alves 2014년 5월 26일
댓글: Star Strider 2014년 5월 26일
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??

채택된 답변

Star Strider
Star Strider 2014년 5월 26일
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
Douglas Alves
Douglas Alves 2014년 5월 26일
I understand it perfectly. Thanks a lot!!
Star Strider
Star Strider 2014년 5월 26일
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.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Elementary Math에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by