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 件のコメント
Stephen23
Stephen23 2021 年 5 月 6 日
As an aside, note that the square brackets here are superfluous and should be removed:
a = [(v_f - v_0) ./ t];
% ^ remove these ^

サインインしてコメントする。

回答 (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.
  2 件のコメント
Carlos Puente
Carlos Puente 2021 年 5 月 5 日
So I should do something else, or is there a solution for it?
the cyclist
the cyclist 2021 年 5 月 6 日
What value do you want d_a_const to take when a is not zero?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by