Functions

Matlab functions are called like C functions which can return matrices of various sizes:

>> A = rand(4)               % your results may vary

A =

    0.9501    0.8913    0.8214    0.9218
    0.2311    0.7621    0.4447    0.7382
    0.6068    0.4565    0.6154    0.1763
    0.4860    0.0185    0.7919    0.4057

>> detA = det( A )

d =

     0.1155

>> size( A )

ans =

     4     4

Matlab functions are aware of how many variables the output is being assigned to. In the above examples,

Unlike most programming languages, a Matlab functions are aware of how many output, rand(4) and det(A) are being assigned to one variable, while size( A ) is not being assigned to any variables.

Using size as an example, the output can be assigend to zero, one, or two variables:

>> B = rand( 4, 7 );      % a 4 × 7 matrix
>> size( B )

ans =

     4     7

>> sizeB = size( B )

sizeB =

     4     7

>> [mB nB] = size( B )

mB =

     4

nB =

     7

In the third example, the first variable is assigned the row dimension of B, and the second variable is assigned the column dimension.

Assigning to multiple outputs does not occur automatically:

>> C = [1 2; 3 4]

C =

     1     2
     3     4

>> [a b] = diag( C )
??? Error using ==> diag
Too many output arguments.

In some cases, you can get more information out of a function if you assign the output to more than one variable. For example, the eigenvalue function eig returns a row vector of eigenvalues if the output is being assigned to zero or one variables, but it returns two matrices if the output is assigned to two variables:

>> D = [1 2; 3 4]

D =

     1     2
     3     4

>> evalD = eig( D )

evalD =

   -0.3723
    5.3723

>> [EvecD EvalD] = eig( D )    % note the eigenvalues are on the diagonal

EvecD =

   -0.8246   -0.4160
    0.5658   -0.9094

EvalD =

   -0.3723         0
         0    5.3723

If the function is being called from within an expression, it is assumed that it is being assigned to zero variables:

>> length( eig( D ) )

ans =

     2