Effacer les filtres
Effacer les filtres

Using while loops, to sort and index arrays.

9 vues (au cours des 30 derniers jours)
Kevin Bafe
Kevin Bafe le 3 Avr 2019
Commenté : Kevin Bafe le 7 Avr 2019
Can some one please help me with a homework problem thats driving me crazy!!
I need to make a function that scans the grades of a class, each time it sees a fail, a counter goes up by one.
This counter then saves the grade and position of the failing grade on the list.
This has to be done using a 'While loop"
I have written working code, however, my while loop is just as frivolous as the counter in countroles.
Marks = randi([0 100],1,10)
Fail = [0:40];
no = ismember([Marks],[Fail]);
B = sum(no);
Counter = 0;
while Counter < B
Counter = Counter + 1
end
[c,x] = find(no == 1);
Index = x
Results = Marks(x)
if a == 0
Results = "'Happy Days, No Fails' "
Index = 0
end
Thank you!
  1 commentaire
Geoff Hayes
Geoff Hayes le 3 Avr 2019
Kevin - the intent of the exercise may be to use the while loop to iterate over each element in the array (the Marks variable from above). When you encounter a failing grade, then you increment your counter and store the index of the fail. (Perhaps this way rather than using ismember.)

Connectez-vous pour commenter.

Réponse acceptée

Manuel Schmidberger
Manuel Schmidberger le 5 Avr 2019
Maybe you can use anything like:
Marks = randi([0 100],1,10)
Fail = [0:40];
i=1;
FailCount=0;
while i<=length(Marks)
if any(Marks(i)<=(Fail))
FailCount=FailCount+1;
end
i=i+1;
end
But to be honest I'm curious about the homework since this is a really bad problem or bad idea to use a while loop since
sum(ismember(Marks,Fail))
solves the problem and
find(ismember(Marks,Fail)==1)
gives the positions of Fails.
  1 commentaire
Kevin Bafe
Kevin Bafe le 7 Avr 2019
Thank you, i ended up figuring it out. ill post code below.
The problem was to practice while loops. it was made clear that there are mulitple was to solve it in the question.
thank you for your help!
Results=0;
Index=0;
N = 1;
p=0;
counter = 0;
while N <= length(Marks)
if Marks(N)< 40
counter = counter + 1;
Results(counter) = Marks(N);
Index(counter) = N;
end
N=N+1;
end
if size(Index) == 0;
disp('Happy Days, No Fails')
end
disp(Index)
disp(Results)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by