How to change output of function?

3 views (last 30 days)
Antonio Sarusic
Antonio Sarusic on 4 May 2022
Commented: Monica Roberts on 6 May 2022
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)

Answers (1)

Monica Roberts
Monica Roberts on 4 May 2022
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 Comments
Jan
Jan on 6 May 2022
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 on 6 May 2022
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'.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!