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.

2 views (last 30 days)
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

Answers (1)

the cyclist
the cyclist on 5 May 2021
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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!