First and last occurrence of an element in an array
20 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Femi Bolarinwa
il 19 Nov 2020
Risposto: James Tursa
il 19 Nov 2020
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 Commenti
James Tursa
il 19 Nov 2020
What have you done so far? What specific problems are you having with your code?
Risposta accettata
James Tursa
il 19 Nov 2020
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 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!