Index for loop
2 ビュー (過去 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 で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!