Index for loop

조회 수: 5 (최근 30일)
Julia m
Julia m 2012년 5월 17일
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

답변 (2개)

per isakson
per isakson 2012년 5월 17일
Try
ix = find( list == x );
  댓글 수: 1
Walter Roberson
Walter Roberson 2012년 5월 17일
ix = find(list == x, 1, 'first');

댓글을 달려면 로그인하십시오.


Geoff
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).

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by