Write a function called myfind that will search for a key in a vector and return
ID: 3934762 • Letter: W
Question
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.
Explanation / Answer
% 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
%}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.