Search code examples
arraysmatlabrandomfunction-handle

Create an N by 1 Function Handle that Returns an array of All Zeros and Populates one Index in the Array with another Function Handle


I have the following function handle:

f = @(t)f_0.*sin(alpha.*t).*cos(beta.*t);

I want to create an N by 1 function handle "array" called F (I know that you can't have an array of function handles in MATLAB) that places f at any random index position within the function handle "array." All other entries should be zero. N is any integer value.

For example, if N = 3, the correct solution is:

F = @(t) [f(t); 0; 0]

Two other correct solutions are:

F = @(t) [0; 0; f(t)]

and

F = @(t) [0; f(t); 0]

since f(t) can be placed at any random index i within F.

What is the best way to do this for any arbitrary N?


Solution

  • As I understand the question the following function returns the requested function handle:

    function F = farray (f, N)
        r = randi(N);
        F = @(t) [zeros(r-1, 1); f(t); zeros(N-r, 1)];
    end
    

    It can be used as:

    f = @(t)f_0.*sin(alpha.*t).*cos(beta.*t);
    N = 3;
    F = farray(f, N);