Function definition are not supported in this context. Functions can only be created as local or nested functions in code files
Mostra commenti meno recenti
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
Risposta accettata
Più risposte (0)
Categorie
Scopri di più su Logical in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!