I put an if loop inside a function and it doesn't work. It doesn't work with any loop or anything I try to add like a sub-function.

1 次查看(过去 30 天)
The second function in this script, d_a_const = dist_cons(v_0, v_f, t, a), doesn't work with the if loop inside it. I don't know how to fix it. It doesn't matter if I work with matrices or not, it just won't run if the loop is inside the function.
It shows this error:
Output argument "d_a_const" (and maybe others) not assigned during call to "CP_4>dist_cons".
Error in CP_4 (line 12)
d_a_const = dist_cons(v_0, t, a)
% Ejercicio 4
clc
clear
t = [1 2 1 1 3 8];
v_f = [10 10 24 24 0 0];
v_0 = [0 10 10 24 24 0];
x_0 = 0;
a = acl(v_f, v_0, t)
d_a_const = dist_cons(v_0, t, a)
function [a] = acl(v_f, v_0, t)
a = [(v_f - v_0) ./ t];
end
function d_a_const = dist_cons(v_0, t, a)
if a == 0
d_a_const = v_0 + (0.5) .* a(d_a_const) .* (t.^2);
end
end

回答(1 个)

the cyclist
the cyclist 2021-5-5
Because a is a vector, the if statement
if a == 0
...
end
will only be entered if a==0 for all elements of a. An if statement on a vector does not "loop" over the individual elements.
So, your if statement is never entered, and d_a_const is never assigned.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by