Search code examples
arraysfunctionmatlabcell-arrayfunction-handle

Populate Every other Element of Array with Function Handle MATLAB


I have the following function:

function F = farray (f,N)
F = {@(t) zeros(N,1)};
    for i=1:N
        if mod(i,2)==0
            F{i}=f(t);
        end
    end
F = cell2mat(F);
end

f is a function handle of time, that is f=@(t)f(t). N dictates the size of the output array F. Similar to f, F is also a function of time. I would like to populate every other entry of F with f, and return F as a function handle that converts to a double array when substituted for t. All other entries in the array should be zero. I thought what I have above would work, but that is not the case. Where am I going wrong here?


Solution

  • I would do this this way: write a function that creates the desired output array for a given f, t and N, and then use an anonymous function to fill in the existing definitions of f and N so that you have a function only of t.

    f = …
    N = …
    F = @(t) farray(f, t, N);
    
    function out = farray (f, t, N)
        out = zeros(N,1);
        out(2:2:end) = f(t);
    end