Borrar filtros
Borrar filtros

Using while loops, to sort and index arrays.

9 visualizaciones (últimos 30 días)
Kevin Bafe
Kevin Bafe el 3 de Abr. de 2019
Comentada: Kevin Bafe el 7 de Abr. de 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 comentario
Geoff Hayes
Geoff Hayes el 3 de Abr. de 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.)

Iniciar sesión para comentar.

Respuesta aceptada

Manuel Schmidberger
Manuel Schmidberger el 5 de Abr. de 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 comentario
Kevin Bafe
Kevin Bafe el 7 de Abr. de 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)

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by