Search code examples
matlabfunctionmatrixmat-file

Using a matrix of data inside a function in MATLAB


I need to know how to extract an arbitrary entry of a matrix inside a function. Say a function f gets two extra input arguments i and j to extract element a(i,j) of a fixed real-valued matrix. The matrix is in the workspace, and is of large size. The function f is inside a long iterative algorithm. Having the whole matrix a recalled in each iteration will reduce the speed significantly. This matrix needs either to be defined as a function (so that it can be recalled inside a function), or to be loaded from a mat-file. The first option seems to be more efficient, but have no idea how to save a matrix as function.


Solution

  • I do not understand your question.

    Suppose you have array arr. You can do arr(i,j) to access elements of it.

    Suppose you also have a function func(arr, i, j) in the body of the function you can easily access arr(i,j) with the parameters.

    If func returns an array, then you can do var = func(arr); var(i,j)

    If you want a matrix of functions, make handles to them and store that in an array;

    a = @func_a;
    b = @func_b;
    c = @func_c;
    funcarray = [a b c];