How do I find first index of a value in an array?

I have the skeleton code
Function i = find_first(array, value)
% FIND_FIRST Find first index of a value in an array.
% I = FIND_FIRST(ARRAY, VALUE) returns the index I into the ARRAY where the
% first occurrence of VALUE is found. If VALUE is not in ARRAY, then an error is raised.
n = length(array);
i = 1;
while ??? && ???
i = i + 1;
end
%Check if value was not found
if ???
error('VALUE was not found.');
end
I can only use this model to answer the question. I have tried for a couple hours and I just can't crack it. Any help / tips would be appreciated :).

5 Comments

function i = find_first(array,value)
i=find(array==value,'first');
if isempty(i)==1
disp(strcat(num2str(value),' was not found'))
end
end
Josh, is there a specific reason (homework?) why you can only use this model?
Well, first off, how might you determine when to quit and would that not be the while condition?
Second, you'll have to do the comparison-checking inside the loop to have anything to compare and then how do you reference the array inside the loop?
Let's see your attempts to answer those issues since is obviously a homework problem.
Using length is a really bad idea. Whoever wrote that template has done a lot of beginners a disservice by teaching them to use a function that would be better replaced by numel or size. In this case numel would be much better, and would actually loop over all elements of the input array. Unlike length.
Exactly what is looking for, is this? value=array(1);

Sign in to comment.

Answers (0)

Categories

Asked:

on 17 May 2018

Commented:

on 20 May 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!