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)
댓글 수: 0
답변 (1개)
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
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
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 Exchange에서 Function Creation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!