MATLAB Answers

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 view (last 30 days)
Carlos Puente on 5 May 2021
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 CommentShowHide None
Stephen Cobeldick on 6 May 2021
As an aside, note that the square brackets here are superfluous and should be removed:
a = [(v_f - v_0) ./ t];
% ^ remove these ^

Sign in to comment.

Answers (1)

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.
2 CommentsShowHide 1 older comment
the cyclist on 6 May 2021
What value do you want d_a_const to take when a is not zero?

Sign in to comment.

R2018a

Community Treasure Hunt

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

Start Hunting!