How to change output of function?

13 ビュー (過去 30 日間)
Antonio Sarusic
Antonio Sarusic 2022 年 5 月 4 日
コメント済み: Monica Roberts 2022 年 5 月 6 日
Hello,
My problem is that when my if-statement is not fullfiled and the code executes the else-statement I just want it to return the text message. But i have to assign some value to W and if i do so and call the function it also shows me that A is empty. Is it possible to chang this that it just shows me the error message without the empty Value of A?
function W = hat(w)
sz = size(w);
if sz == [3 1]
W = [0 -w(3) w(2); w(3) 0 -w(1); -w(2) w(1) 0];
else
disp('Variable w has to be a 3-component vector!');
W=[];
end
end
a = [1;2];
A = hat(a)

回答 (1 件)

Monica Roberts
Monica Roberts 2022 年 5 月 4 日
You can use return to exit the function, but depending on how you use this function, it's usually helpful to have a default value for the output. You could also use MATLAB's built-in warning function:
function W = hat(w)
sz = size(w);
if sz == [3 1]
W = [0 -w(3) w(2); w(3) 0 -w(1); -w(2) w(1) 0];
else
warning('Variable w has to be a 3-component vector!');
return
end
end
  4 件のコメント
Jan
Jan 2022 年 5 月 6 日
This is fragile:
sz = size(w);
if sz == [3 1]
== is the elementwise comparison. If the input w has more then 2 dimension, the comparison fails. Prefer the safer:
sz = size(w);
if isequal(sz, [3 1])
Or:
if isrow(w) && numel(w) == 3
Monica Roberts
Monica Roberts 2022 年 5 月 6 日
Very true, though unrelated to the original question. I'd probably also suggest a more specific warning 'Input variable must be a 3 x 1 vector'.

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

カテゴリ

Help Center および File ExchangeFunction Creation についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by