Vectors as input and output in a function

17 ビュー (過去 30 日間)
Luciano Montanelli
Luciano Montanelli 2021 年 5 月 27 日
コメント済み: Walter Roberson 2021 年 5 月 28 日
I am calling this function in another script. The function is called 'a.m' and is in the same folder as the script. aceleracion should be an output vector and u is an input vector. I am getting the following error:
Unable to perform assignment because the indices on the left side are not compatible with the size of
the right side.
Error in a (line 11)
aceleracion(indtiempo)=h*w*cos(w*u(indtiempo)-pi);
Error in Encoder_interpolacion_lineal_online_y_offline_con_aceleracion (line 319)
aang=a(taang);
Thanks in advance.
function [aceleracion] = a(u)
global periodo;
global h;
global w;
for indtiempo=1:length(u)
if u(indtiempo)<=periodo/2
aceleracion(indtiempo)=h*w*cos(w*u(indtiempo));
else
aceleracion(indtiempo)=h*w*cos(w*u(indtiempo)-pi);
end
end
end
  2 件のコメント
Walter Roberson
Walter Roberson 2021 年 5 月 28 日
Put a breakpoint in at the for loop. When the code stops, examine
size(periodo)
size(h)
size(w)
size(w)
Luciano Montanelli
Luciano Montanelli 2021 年 5 月 28 日
There is the problem. It doesn't recognize my global variables. How can I solve this? Thanks in advance for helping.

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

採用された回答

Jan
Jan 2021 年 5 月 28 日
You get the usual trouble with global variables: It is a horror to find out, which code was responsible for the last change. In your case the values are empty matrices and you do not know why. I do not know this also. How could I: you did not show us, where these variables are defined.
You have to mark the global variables as global in each function you use it. But the best idea is to avoid globals, because they are a shot in your knee. In your case the code seems to have less then 100 lines. In larger projects, e.g. with 100'000 lines of code written by serveral programmers, a confusion with globals can make the code unusable, because it is far too complex to expand or debug it. So start to get familiar with the good programming practice and provide the values as input parameters instead of distributing them as globals.
  3 件のコメント
Luciano Montanelli
Luciano Montanelli 2021 年 5 月 28 日
Thanks Walter Roberson as well.

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by