204k views
1 vote
A function may receive less arguments than defined in the function header. The built-in function nargin tells the actual number of input arguments received in your custom function. For example,

- aFunction() -> using nargin inside aFunction will return 0
- aFunction(9) -> using nargin inside aFunction will return 1
- aFunction([3,2,2], [1,2,3]) -> using nargin inside aFunction will return 2 (counting two input arrays, not 6 elements)
Try varying input arguments and running the examples in the "Code to Call Your Function" until you understand how nargin function works (a similar built-in function, nargout, for the output arguments also exists but we won't need it for this programming test).
Now, write a function with an n-way if-else (or switch) statement that will do the following:
- Given zero input arguments, return two empty arrays.
- Given one input argument A (it will always be a numeric array), return return two subarrays where the first output array contains A's elements at odd indices and the second output array contains A's elements at even indices.
- Given two input arguments A and n (the first input argument is always a numeric and the second input argument is always an integer), return A 's nth element A(n) and the remainder of A without its nth element.
When given input arguments, you may assume the arguments are all valid, i.e., index will never be out of bounds.
Examples
- aFunction() returns [] and []
- aFunction ([5,3,9,2]) returns [5,9] and [3,2]
- aFunction([5,3,9,2],3) returns 9 and [5,3,2]
Task
Write a function aFunction that takes up to two input arguments and returns two output values.

1 Answer

2 votes

Final answer:

The given question requires writing a MATLAB function that returns different outputs based on the number of input arguments received. The function should handle zero, one, or two input arguments and produce the corresponding output arrays.

Step-by-step explanation:

The given problem involves writing a function with an n-way if-else statement in MATLAB. The function will return different outputs based on the number of input arguments received. Here is the implementation:

function [out1, out2] = aFunction(varargin)

If nargin is 0, return two empty arrays: out1 = []; and out2 = [];If nargin is 1, extract the odd and even indexed elements from the input array:Initialize two arrays odds = []; and evens = [];Using a for loop, iterate over the elements of the input array and append odd-indexed elements to odds and even-indexed elements to evens.Return odds and evens as out1 and out2 respectively.If nargin is 2, return the nth element of the first input array and the remaining array without the nth element.
User Deng Steve
by
7.8k points