Index for loop
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Geoff
2012-5-17
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!