Write a function called myfind that will search for a key in

Write a function called myfind that will search for a key in a vector and return the indices of all occurrences of the key, like the built-in find function. It will receive two arguments— the vector and the key—and will return a vector of indices or the empty vector [ ] if the key is not found. The function will be invoked as follows:

idx = myfind(vec, key);

Following is an example of correct function behavior:

>> vec = randi([5, 10], 1, 10)

vec = 5 10 10 7 9 5 7 10 9 10

>> key = 10;

>> idx = myfind(vec, key)

idx = 2 3 8 10

>> key = 2;

>> idx = myfind(vec, key)

idx = Empty matrix: 1-by-0

Do not use the in-built find function.

Solution

% matlab code find all index of key in vector

function idx = myfind(vec, key)
    index = 1;
    for i=1:length(vec)
        if vec(i) == key
           idx(index) = i;
           index = index + 1;
        end
    end
end

vec = randi([5, 10], 1, 10);
disp(\"Vector: \");
disp(vec);
key = 10;
fprintf(\"\ Key: %d\ \",key);
idx = myfind(vec, key);
disp(\"\ Index: \");
disp(idx);

%{
sample output:

Vector:
   10   10    8   10    5   10    5    8    9    5

Key: 10

Index:
   1   2   4   6

%}

Write a function called myfind that will search for a key in a vector and return the indices of all occurrences of the key, like the built-in find function. It

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site