How can I solve a problem related to the output argument.
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Fidele Adanvo
le 18 Nov 2020
Commenté : Star Strider
le 18 Nov 2020
% I will make the code simpler. Let's assume I have this code. And depending on the input value I want to show assign a=10 and b=5 different values (disregard the %value of the output C) or assign c=100 a value and disregard a and b.
function [a,b,c,d] = trial_function(num)
if num==2
a=4;
b=5
elseif num==4
c=100;
d=230
end
%I am getting an error. Output argument "b" (and maybe others) not assigned during call to
%Please, can you help me.Thank you.
0 commentaires
Réponse acceptée
Ameer Hamza
le 18 Nov 2020
Modifié(e) : Ameer Hamza
le 18 Nov 2020
The name of output argument does not matte outside the function. If you just want to output two values for each case, just use
function [a,b] = trial_function(num)
if num==2
a=4;
b=5;
elseif num==4
a=100;
b=230;
end
Regardless, If you want to output 3rd and 4th argument in 2nd case, then you can set a and b to empty vectors
[~,~,x,y] = trial_function(4)
function [a,b,c,d] = trial_function(num)
if num==2
a=4;
b=5;
elseif num==4
a = [];
b = [];
c=100;
d=230;
end
end
If you want to output variable number of output arguments, then use varargout: https://www.mathworks.com/help/matlab/ref/varargout.html
Plus de réponses (1)
Star Strider
le 18 Nov 2020
The way I usually deal with this is to define all the outputs as NaN in the beginning of the function. The ones that are assigned in the function will overwrite tha NaN value, and it is also easy to determine the values that were not assigned.
Example —
function [a,b,c,d] = trial_function(num)
[a,b,c,d] = deal(NaN);
if num==2
a=4;
b=5
elseif num==4
c=100;
d=230
end
end
.
2 commentaires
Star Strider
le 18 Nov 2020
In my approach, the outputs are assigned NaN until they are assigned other values in the if blocks. If they are not assigned other values, they remain NaN. Assign them any value you wish, then modify that value later in the code.
Assigning them a specific value (whether NaN, 0, or something else) avoids throwing the warning or error if the values are not assigned in the if blocks. It will also indicate which values are not assigned, since those will be NaN (or any other default value).
Voir également
Catégories
En savoir plus sur Whos dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!