0
0
MATLABdata~10 mins

Variable arguments (varargin, varargout) in MATLAB - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a function that accepts a variable number of input arguments.

MATLAB
function varargout = myFunction([1])
% This function accepts variable input arguments
n = nargin;
varargout = cell(1, n);
Drag options to blanks, or click blank then click option'
Avarargin
Bvarargout
Cinput
Dargs
Attempts:
3 left
💡 Hint
Common Mistakes
Using varargout instead of varargin for inputs
Using a regular variable name instead of varargin
2fill in blank
medium

Complete the code to access the number of input arguments inside the function.

MATLAB
function output = countInputs(varargin)
numArgs = [1];
output = numArgs;
Drag options to blanks, or click blank then click option'
Avarargin
Blength(varargin)
Cnargout
Dnargin
Attempts:
3 left
💡 Hint
Common Mistakes
Using nargout which counts output arguments
Using length(varargin) which works but nargin is preferred
3fill in blank
hard

Fix the error in the function to correctly return variable output arguments.

MATLAB
function varargout = exampleFunc(varargin)
for k = 1:[1]
    varargout{k} = varargin{k}^2;
end
Drag options to blanks, or click blank then click option'
Anargout
Bnargin
Clength(varargin)
Dnumel(varargout)
Attempts:
3 left
💡 Hint
Common Mistakes
Using nargin which counts inputs instead of outputs
Using length(varargin) which counts inputs, not outputs
4fill in blank
hard

Fill both blanks to create a function that sums all input arguments and returns the sum and count.

MATLAB
function [total, count] = sumInputs([1])
total = 0;
for i = 1:[2]
    total = total + varargin{i};
end
count = nargin;
Drag options to blanks, or click blank then click option'
Avarargin
Bnargin
Clength(varargin)
Dvarargout
Attempts:
3 left
💡 Hint
Common Mistakes
Using nargout instead of length(varargin) for loop count
Using varargout instead of varargin for inputs
5fill in blank
hard

Fill all three blanks to create a function that returns the first input squared, the number of inputs, and the number of outputs.

MATLAB
function [out1, out2, out3] = multiOutput([1])
out1 = varargin{1}^2;
out2 = [2];
out3 = [3];
Drag options to blanks, or click blank then click option'
Avarargin
Bnargin
Cnargout
Dlength(varargin)
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up nargin and nargout
Using length(varargin) instead of nargin