Index for loop
3 views (last 30 days)
Show older comments
Hi. I need to find the index corresponding to the variable in the matrix here is what i have
function linear = linearSearch(list, x)
i=1;
for item = list(1:i) if x == list(i); i = x; else i = '-1'; end end
0 Comments
Answers (2)
Geoff
on 17 May 2012
To do this in a loop (not the find command), you are doing a few things wrong. Here is your code:
i=1;
for item = list(1:i) % 1:i is going to be a single value: 1
%\ Also, you don't loop over the values in list - you
%\ need to loop over the indices.
if x == list(i); % You are using the wrong index - should be: item
i = x; % x is the value you are searching for, not the index!
else
i = '-1'; % You just assigned a string, not a number
end
end
Finally, your function's return value is linear, but you are storing your answer in i. Assigning -1 to i every single time you have no match is pointless. It will also overwrite your result because you never break out of the loop when you find it.
So I'm sorry to report that just about everything is wrong with that code! =)
However, here is the corrected version:
linear = []; % Use empty to denote 'not found'. You can use -1 or 0 instead.
for item = 1:numel(list)
if list(item) == x
linear = item;
break;
end
end
I have assumed here that you simply want to find the index of the first matching value. If you want to find all the indices, it just takes a small modification -- remove the 'break', and do:
linear(end+1) = item;
Note that the above relies on 'linear' being initialised to the empty set -- not -1 or 0 (or anything else for that matter).
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!