Matlab script and function m-files


Download 305 Kb.
bet4/4
Sana29.03.2023
Hajmi305 Kb.
#1306768
1   2   3   4
Bog'liq
functions in MATLAB

MATLAB Function Files

  • Lect 19 P.
  • Winter Quarter
  • Referring to the function, the comments immediately following the function definition statement are the "help" for the function. The MATLAB command:
  • >>help swap %displays:
  • The function swap receives two values, swaps them,
  • and returns the result. The syntax for the call is
  • [a, b] = swap (a, b) where the a and b in the ( ) are the
  • values sent to the function and the a and b in the [ ] are
  • returned values which are assigned to corresponding
  • variables in your program.

MATLAB Function Files

  • Lect 19 P.
  • Winter Quarter
  • The MATLAB function must be in the current working directory. If it is not, the directory must be changed before calling the function.
  • If MATLAB cannot find the function or its syntax does not match the function call, an error message will appear. Failure to change directories often results in the error message:
  • Undefined function or improper matrix assignment.

MATLAB Function Files

  • Lect 19 P.
  • Winter Quarter
  • When the function file is not in the current working directory, a cd or chdir command may be issued to change the directory.
  • >> cd a:\ % Make a:\ the current working directory

MATLAB Function Files

  • Lect 19 P.
  • Winter Quarter
  • Unlike C, a MATLAB variable does not have to be declared before being used, and its data type can be changed by assigning a new value to it.
  • For example, the function factorial ( ) on the next slide returns an integer when a positive value is sent to it as an argument, but returns a character string if the argument is negative.

MATLAB Function Files

  • Lect 19 P.
  • Winter Quarter
  • function [n] = factorial (k)
  • % The function [n] = factorial(k) calculates and
  • % returns the value of k factorial. If k is negative,
  • % an error message is returned.
  • if (k < 0) n = 'Error, negative argument’;
  • elseif k<2 n=1;
  • else
  • n = 1;
  • for j = [2:k] n = n * j; end
  • end

Download 305 Kb.

Do'stlaringiz bilan baham:
1   2   3   4




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling