How to change output of function?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (1)
Monica Roberts
el 4 de Mayo de 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 comentarios
Jan
el 6 de Mayo de 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
el 6 de Mayo de 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'.
Ver también
Categorías
Más información sobre Signal Analysis en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!