First and last occurrence of an element in an array

30 ビュー (過去 30 日間)
Femi Bolarinwa
Femi Bolarinwa 2020 年 11 月 19 日
回答済み: James Tursa 2020 年 11 月 19 日
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
James Tursa 2020 年 11 月 19 日
What have you done so far? What specific problems are you having with your code?
Femi Bolarinwa
Femi Bolarinwa 2020 年 11 月 19 日
編集済み: Femi Bolarinwa 2020 年 11 月 19 日
L = length(A);
i = 1;
while i <= L
x = A(i);
y = A(i+1);
if x == 7 && y == 7
break
end
i = i + 1;
end
The problem is this code only detects when 7 is repeated consecutively. I need to be able incorporate some kind of memory in the loop to detect 7 even if its appear somewhere else in the array

サインインしてコメントする。

採用された回答

James Tursa
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 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by