Define a function in each with two argument parameter input and output. Reads a
ID: 3639539 • Letter: D
Question
Define a function in each with two argument parameter input and output. Reads a file from input file and gives output to output file. Make sure for output, each char will be in new line enclosed with '>' and '<'. Suppose you have hello in input file. Output supposed to be.>h<
>e<
>l<
>l<
>o<
Explanation / Answer
You can specify a file name argument using the MATLAB command or function syntax. For example, either of the following are acceptable. (The .mat file extension is optional for save and load): load mydata.mat % Command syntax load('mydata.mat') % Function syntax If you assign the output to a variable, you must use the function syntax: savedData = load('mydata.mat') Specify ASCII files as shown here. In this case, the file extension is required: load mydata.dat -ascii % Command syntax load('mydata.dat','-ascii') % Function syntax Determining File Names at Run-Time. There are several ways that your function code can work on specific files without your having to hardcode their file names into the program. You can Pass the file name as an argument: function myfun(datafile) Prompt for the file name using the input function: filename = input('Enter name of file: ', 's'); Browse for the file using the uigetfile function: [filename, pathname] = uigetfile('*.mat', 'Select MAT-file'); Passing Function Handle Arguments The MATLAB function handle has several uses, the most common being a means of immediate access to the function it represents. You can pass function handles in argument lists to other functions, enabling the receiving function to make calls by means of the handle. To pass a function handle, include its variable name in the argument list of the call: fhandle = @humps; x = fminbnd(fhandle, 0.3, 1); The receiving function invokes the function being passed using the usual MATLAB calling syntax: function [xf, fval, exitflag, output] = ... fminbnd(fhandle, ax, bx, options, varargin) . . . 113 fx = fhandle(x, varargin{:}); Back to Top Output Arguments To receive data output from a function, you must call the function with function syntax rather than command syntax. For a description of these syntaxes, see Command vs. Function Syntax. Assigning Output Arguments Use the syntax shown here to store any values that are returned by the function you are calling. To store one output, put the variable that is to hold that output to the left of the equal sign: vout = myfun(vin1, vin2, ...); To store more than one output, list the output variables inside square brackets and separate them with commas or spaces: [vout1 vout2 ...] = myfun(vin1, vin2, ...); The number of output variables in your function call statement does not have to match the number of return values declared in the function being called. For a function that declares N return values, you can specify anywhere from zero to N output variables in the call statement. Any return values that you do not have an output variable for are discarded. Functions return output values in the order in which the corresponding output variables appear in the function definition line within the file. This function returns 100 first, then x * y, and lastly x.^2: function [a b c] = myfun(x, y) b = x * y; a = 100; c = x.^2; If called with only one output variable in the call statement, the function returns only 100 and discards the values of b and c. If called with no outputs, the functions returns 100 in the MATLAB default variable ans. Assigning Optional Return Values The section Passing Variable Numbers of Arguments describes the method of returning optional outputs in a cell array called varargout. A function that uses varargout to return optional values has a function definition line that looks like one of the following: function varargout = myfun(vin1, vin2, ...) function [vout1 vout2 ... varargout] = myfun(vin1, vin2, ...) The code within the function builds the varargout cell array. The content and order of elements in the cell array determines how MATLAB assigns optional return values to output variables in the function call. In the case where varargout is the only variable shown to the left of the equal sign in the function definition line, MATLAB assigns varargout{1} to the first output variable, varargout{2} to the second, and so on. If there are other outputs declared in the function definition line, then MATLAB assigns those outputs to the leftmost output variables in the call statement, and then assigns outputs taken from the varargout array to the remaining output variables in the order just described. This function builds the varargout array using descending rows of a 5-by-5 matrix. The function is capable of returning up to six outputs: function varargout = byRow(a) varargout{1} = ' With VARARGOUT constructed by row ...'; for k = 1:5 row = 5 - (k-1); % Reverse row order varargout{k+1} = a(row,:); end Call the function, assigning outputs to four variables. MATLAB returns varargout{1:4}, with rows of the matrix in varargout{2:4} and in the order in which they were stored by the function: [text r1 r2 r3] = byRow(magic(5)) text = With VARARGOUT constructed by row ... r1 = 11 18 25 2 9 r2 = 10 12 19 21 3 r3 = 4 6 13 20 22 A similar function builds the varargout array using diagonals of a 5-by-5 matrix: function varargout = byDiag(a) varargout{1} = ' With VARARGOUT constructed by diagonal ...'; for k = -4:4 varargout{k + 6} = diag(a, k); end Call the function with five output variables. Again, MATLAB assigns elements of varargout according to the manner in which it was constructed within the function: [text d1 d2 d3 d4] = byDiag(magic(5)) text = With VARARGOUT constructed by diagonal ... d1 = 11 d2 = 10 18 d3 = 4 12 25 d4 = 23 6 19 2 Returning Modified Input Arguments If you pass any input variables that the function can modify, you will need to include the same variables as output arguments so that the caller receives the updated value. For example, if the function readText, shown below, reads one line of a file each time is it called, then it must keep track of the offset into the file. But when readText terminates, its copy of the offset variable is cleared from memory. To keep the offset value from being lost, readText must return this value to the caller: function [text, offset] = readText(filestart, offset) Back to Top Passing Arguments in Structures or Cell Arrays Instead of requiring an additional argument for every value you want to pass in a function call, you can package them in a MATLAB structure or cell array. Checking the Number of Input Arguments The nargin and nargout functions enable you to determine how many input and output arguments a function is called with. You can then use conditional statements to perform different tasks depending on the number of arguments. For example, function c = testarg1(a, b) if (nargin == 1) c = a .^ 2; elseif (nargin == 2) c = a + b; end Given a single input argument, this function squares the input value. Given two inputs, it adds them together. Here is a more advanced example that finds the first token in a character string. A token is a set of characters delimited by white space or some other character. Given one input, the function assumes a default delimiter of white space; given two, it lets you specify another delimiter if desired. It also allows for two possible output argument lists: function [token, remainder] = strtok(string, delimiters) % Function requires at least one input argument if nargin < 1 error('Not enough input arguments.'); end token = []; remainder = []; len = length(string); if len == 0 return end % If one input, use white space delimiter if (nargin == 1) delimiters = [9:13 32]; % White space characters end i = 1; % Determine where nondelimiter characters begin while (any(string(i) == delimiters)) i = i + 1; if (i > len), return, end end % Find where token ends start = i; while (~any(string(i) == delimiters)) i = i + 1; if (i > len), break, end end finish = i - 1; token = string(start:finish); % For two output arguments, count characters after % first delimiter (remainder) if (nargout == 2) remainder = string(finish+1:end); end The strtok function is a MATLAB file in the strfun folder. Note The order in which output arguments appear in the function declaration line is important. The argument that the function returns in most cases appears first in the list. Additional, optional arguments are appended to the list. Passing Optional Arguments to Nested Functions You can use optional input and output arguments with nested functions, but you should be aware of how MATLAB interprets varargin, varargout, nargin, and nargout under those circumstances. varargin and varargout are variables and, as such, they follow exactly the same scoping rules as any other MATLAB variable. Because nested functions share the workspaces of all outer functions, varargin and varargout used in a nested function can refer to optional arguments passed to or from the nested function, or passed to or from one of its outer functions. nargin and nargout, on the other hand, are functions and when called within a nested function, always return the number of arguments passed to or from the nested function itself. Using varargin and varargout. varargin or varargout used in a nested function can refer to optional arguments passed to or from that function, or to optional arguments passed to or from an outer function. If a nested function includes varargin or varargout in its function declaration line, then the use of varargin or varargout within that function returns optional arguments passed to or from that function. If varargin or varargout are not in the nested function declaration but are in the declaration of an outer function, then the use of varargin or varargout within the nested function returns optional arguments passed to the outer function. In the example below, function C is nested within function B, and function B is nested within function A. The term varargin{1} in function B refers to the second input passed to the primary function A, while varargin{1} in function C refers to the first argument, z, passed from function B: function x = A(y, varargin) % Primary function A B(nargin, y * rand(4)) function B(argsIn, z) % Nested function B if argsIn >= 2 C(z, varargin{1}, 4.512, 1.729) end function C(varargin) % Nested function C if nargin >= 2 x = varargin{1} end end % End nested function C end % End nested function B end % End primary function A Using nargin and nargout. When nargin or nargout appears in a nested function, it refers to the number of inputs or outputs passed to that particular function, regardless of whether or not it is nested. In the example shown above, nargin in function A is the number of inputs passed to A, and nargin in function C is the number of inputs passed to C. If a nested function needs the value of nargin or nargout from an outer function, you can pass this value in as a separate argument, as done in function B. Example of Passing Optional Arguments to Nested Functions. This example references the primary function's varargin cell array from each of two nested functions. (Because the workspace of an outer function is shared with all functions nested within it, there is no need to pass varargin to the nested functions.) Both nested functions make use of the nargin value that applies to the primary function. Calling nargin from the nested function would return the number of inputs passed to that nested function, and not those that had been passed to the primary. For this reason, the primary function must pass its nargin value to the nested functions. function meters = convert2meters(miles, varargin) % Converts MILES (plus optional FEET and INCHES input) % values to METERS. if nargin < 1 || nargin > 3 error('1 to 3 input arguments are required'); end function feet = convert2Feet(argsIn) % Nested function that converts miles to feet and adds in % optional FEET argument. feet = miles .* 5280; if argsIn >= 2 feet = feet + varargin{1}; end end % End nested function convert2Feet function inches = convert2Inches(argsIn) % Nested function that converts feet to inches and adds in % optional INCHES argument. inches = feet .* 12; if argsIn == 3 inches = inches + varargin{2}; end end % End nested function convert2Inches feet = convert2Feet(nargin); inches = convert2Inches(nargin); meters = inches .* 2.54 ./ 100; end % End primary function convert2meters convert2meters(5) ans = 8.0467e+003 convert2meters(5, 2000, 4.7) ans = 8.6564e+003 Ignoring Selected Outputs or Input Arguments Using the tilde (~) operator, you can change the declaration of a function so that it ignores any one or more entries in the input argument list, or you can change the function calling code so that one or more selected values returned by the function are ignored. This can help you to keep your workspace clear of variables you have no use for, and also help you conserve memory. You can ignore unneeded outputs when calling a function: [vOut1, ~, ~, vOut4] = myTestFun; You can ignore arguments in an input argument list when defining certain functions: function myTestFun(argIn1, ~, argIn3);Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.