How to change output of function?

13 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Function Creation 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by