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

68 Views Asked by At

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?

2

There are 2 best solutions below

0
rahnema1 On BEST ANSWER

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);
3
Luis Mendo On

You can have a cell array of function handles. Or a cell array containing a function handle and zeros, if that's what you want:

f = @(t)f_0.*sin(alpha.*t).*cos(beta.*t);
N = 3;
F = repmat({0}, N, 1); % N×1 cell array of zeros
n = randi(N); % random number in [1 2 ... N] with uniform distribution
F{n} = f;