Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

using matlab For this problem you will be asked to modify the function below as

ID: 3801413 • Letter: U

Question


using matlab

For this problem you will be asked to modify the function below as follows: Add an additional input argument (call it use_sel_in) that will allow a user to enter an operation type (addition, subtraction for example). This will always be a numeric argument. If the user enters a 1, they mean to add, if the user enters a 2, they mean to subtract. Add in additional output argument (call user_sel_out) that will allow you to return a string to the user, representing what the chose to do. for example, it the user enters s 1, you should return the string 'addition'. If the user enters a 2, you should always return the string 'subtraction. In the function body, you should do the following: Based on what the user entered for the parameter that you created, you will either add up the first two parameters, or you will subtract the second parameter from the first. Example:first-arg_second_arg. You should return the answer in the output argument result, and you should indicate what the user chose in the output argument that you created, called user_sel-out.

Explanation / Answer

Matlab function function_example.m

function [result,user_sel_out] = function_example(array1,array2,user_sel_in)
% INPUTS:   array1 = is an array of length N
%           array2 = is an array of length N
%           user_sel_in = An integer either 1 or 2
% OUTPUTS: result = an array of length N obtained after performing
%                   the operation specified by the user through user_sel_in
%          user_sel_out = is an string indicating the operation performed
%                          among the first two arguments
N = length(array1);
if(N~=length(array2)) % if the length of the array1 and array2 are not same
    error('First two arguments must be of same length'); % operation cannot be performed
end
if(user_sel_in == 1) % if user_sel_in is one
    user_sel_out = 'addition'; % user_sel_out will be addition
    result = array1+array2; % and perform addition of array1 and array2
elseif(user_sel_in == 2) % if user_sel_in is two
    user_sel_out = 'subtraction';% user_sel_out will be subtraction
    result = array2-array1;% and perform subtraction of array2 from array1
else % if the user_sel_out not 1 and 2
    error('Third argument must be either 1 or 2'); % print an error message
end
end

Testing the function

>> array1 = [1 2 3 4 5 6];
>> array2 = [1 1 1 1 1 1];
>> user_sel_in = 1;
>> [result,user_sel_out] = function_example(array1,array2,user_sel_in)

result =

     2     3     4     5     6     7


user_sel_out =

addition

>> user_sel_in = 2;
>> [result,user_sel_out] = function_example(array1,array2,user_sel_in)

result =

     0    -1    -2    -3    -4    -5


user_sel_out =

subtraction