Hi all, why will my function not run? If p = 1 I want to find the determinant of A, if p = 2 I want to find the trace of A and if p doesn't equal 1 or 2 I want to display the error message. Is my code correct, or is there a better way to do it? And why does the function not run. Thank you!
function [det(A),tr(A)] = myFunction(A,p)
if p == 1
det(A) = det(A);
elseif p == 2
tr(A) = trace(A);
else
disp ('Invalid input')
end

 Respuesta aceptada

Walter Roberson
Walter Roberson el 20 de Nov. de 2017

1 voto

function [detA,trA] = myFunction(A,p)
if p == 1
detA = det(A);
elseif p == 2
trA = trace(A);
else
disp ('Invalid input')
end
However, you are going to have the problem that in each case you are not assigning to one of the output variables. You should check: does the assignment expect you to return the two possibilities to different variables or to just one output?
function result = test(something)
if something == 1
result = 15;
elseif something == 2
result = -10;
else
result = 'What?'
end

4 comentarios

James Crowe
James Crowe el 20 de Nov. de 2017
If one of the value's is not assigned, the result will be equal to null.
if something == 1
result =
end
if that makes sense.
Walter Roberson
Walter Roberson el 20 de Nov. de 2017
In MATLAB, variables that are not assigned have undefined values (with the exception of global and persistent variables, both of which default to [])
Vlad Atanasiu
Vlad Atanasiu el 18 de Dic. de 2020
So: If any outputs of a function are undefined, then Matlab throws an error.
Write a function were the first outputs are not defined:
function [a,b,c] = undefined_output(x)
c = x;
Call the function:
try
[a,b,c] = undefined_output('no error');
disp(c)
catch
disp('error')
end
Answer:
error
Where is this behavior specified in the Matlab documentation?
Not exactly correct. There is only an error if an unassigned output position is assigned to a variable or used in an expression.
try
[a,b] = undefined_output('no error c unused');
disp(b)
catch
disp('error')
end
b okay
try
[a,b,c] = undefined_output('no error c');
disp(b)
disp(c)
catch
disp('error')
end
error
function [a,b,c] = undefined_output(x)
a = x;
b = 'b okay';
end

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Preguntada:

el 20 de Nov. de 2017

Comentada:

el 18 de Dic. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by