Function definition are not supported in this context. Functions can only be created as local or nested functions in code files
217 ビュー (過去 30 日間)
古いコメントを表示
I keep getting this error from 'function vf = collision(v0,next)':
Function definition are not supported in this context. Functions can only be created as local or nested functions in code files.
Here is my code:
clear % clear all variables in the workspace
global m
v = input('enter initial velocities of three cart in [a,b,c] format ');
m = input('enter mass of three cart in [a,b,c] format ');
threshold = input('enter the threshold for energy and momentum checks');
E0 = sum((1/2)*m.*vi.^2); % initial energy before collision, in erg
P0 = sum(m.*vi); % initial momentum before collision, in g*cm/s
count = 0; % initialize a collision counter
while v(1) > v(2) || v(2) > v(3)
count = count + 1; % update collision counter
if v(1) > v(2)
next = 12; % if false, skip to the next IF
end
if v(2) > v(3)
next = 23; % if false, then next = 12
end
if v(1) > v(2) && v(2) > v(3)
next = input('Which carts collide next, 12 or 23? ');
% if false, next = 12 or 23, depending on first two IF statements
end
% output collision # and final velocity
fprintf('There are %u collisions', count)
v = collision(v, next)
% check energy and momentum... output only if there is a problem...
Check_E = E0 - sum(m*(1/2).*v.^2) % Check shoud be zero
Check_P = P0 - sum(m.*v) % Check should be zero
if Check_E > threshold || Check_P > threshold
disp('There is a problem with checks')
Check_E
Check_P
end
end
if count == 0
disp('There is no collision')
else
disp('There are no more collisions')
% ----- define functions -----
function vf = collision(v0,next)
global m
if next == 12
% final velocity of cart#1,in cm/s
vf(1) = ((m(1) -m(2))*v0(1) + 2*m(2)*v0(2))/(m(1) + m(2));
% final velocity of cart#2, in cm/s
vf(2) = (2*m(1)*v0(1) + (m(2)-m(1))*v0(2))/(m(1) + m(2));
vf(3) = v0(3);
end
if next == 23
vf(1) = v0(1);
% final velocity of cart#2, in cm/s
vf(2) = ((m(2)-m(3))*v0(2) + 2*m(3)*v0(3))/(m(2) + m(3));
% final velocity of cart#3, in cm/s
vf(3) = (2*m(2)*v0(2) + (m(3)-m(2))*v0(3))/(m(2) + m(3));
end
end
0 件のコメント
採用された回答
DGM
2022 年 1 月 10 日
編集済み: DGM
2022 年 1 月 10 日
In versions which support local functions in scripts (R2021x does), the functions must be at the end of the file. There aren't enough end statements to make the structure unambigous, but you appear to have the function definition inside of an if-else structure. Either way, just make sure that the function definitions are the last thing in the file and are not inside any other scope.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Graphics Object Programming についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!