Problem with function @(t) [ (1/2)*a*t.^2]
1 回表示 (過去 30 日間)
古いコメントを表示
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??
0 件のコメント
採用された回答
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 件のコメント
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 Center および File Exchange で Data Type Identification についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!