First and last occurrence of an element in an array
22 次查看(过去 30 天)
显示 更早的评论
I want to be able to find the indices of the first and last occurence of a number in an array of any length by using a while or for loop
For example: find the indices of the first and last occurence of 7 in array A = [3 5 3 8 9 7 4 5 7 1 4 9 0 6 8 3 5 9 1 4 7 4 9 3 6 0 2 5 7 8]
Thanks in advance.
2 个评论
James Tursa
2020-11-19
What have you done so far? What specific problems are you having with your code?
采纳的回答
James Tursa
2020-11-19
So the description of the problem doesn't say anything about consecutive values, so the code you have for that should be eliminated. Instead, just ask yourself how you would go about doing this by hand, and then try to turn that into code.
E.g., how would you find the first occurrence? I would start looking from the beginning and when I found the number I would stop looking for it. Also need to account for the possibility that the number isn't there. So pseudo logic for that might be this using your existing framework:
x = 0; % start x out as 0 ... haven't found the first index yet
while i <= L
if x is 0 and A(i) is the number I am looking for % <-- you need to rewrite this logic as actual code
x = i; % save the index
end
i = i + 1;
end
When you get done with this loop, x will either be 0 or it will contain the first index. Or you could use x = [] as the initial condition and have x be empty when nothing is found yet.
Then do the something similar for the last index. Write pseudo logic for this first, and then turn the parts that are not code into actual code. What algorithm could you use? You might run a loop in reverse order and stop looking when you found the number. Or you could run the loop in the normal direction and have slightly different logic. Figure out the algorithm first and run a small example through it by hand. Once you are convinced that your algorithm works, turn it into actual code.
0 个评论
更多回答(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!