#Day5- #100DaysChallenge- Matlab Loops| Linear Search
#Day5-Linear Search
Task: Linear SearchNote: This code can be done using the in-built command. But for the challenge I am trying to avoid those.
a=[1,2,3,1,1,2,3,4,5,1]
In the above vector, we have to find the first occurrence of the given number x
For Example:
If x=3.
Then the code has to return 3 because the index of x=3 is 3 [First Occurrence]
If x=1
Then the code has to return 1 because the index of x=1 is 1[First Occurrence]
If x=4
Then the code has to return 8 because the index of x=4 is 8[First Occurrence]
Matlab Code:
function
loc=lin_search(in_vect,x)
[m,n]=size(in_vect);
loc=-1;
for i=1:1:n
if (x==in_vect(i))&& (loc==-1)
loc=i;
end
end
end
Sample Input and Output
loc=lin_search(a,3)
loc =
3
loc=lin_search(a,1)
loc =
1
loc=lin_search(a,4)
loc =
8
Click Here for video Description
Join us on Telegram: https://t.me/matlabirawen
Join us on Facebook Group:https://www.facebook.com/groups/matlabcodesLinear Search
No comments