Clear Filters
Clear Filters

Using while loops, to sort and index arrays.

9 views (last 30 days)
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 Comment
Geoff Hayes
Geoff Hayes on 3 Apr 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.)

Sign in to comment.

Accepted Answer

Manuel Schmidberger
Manuel Schmidberger on 5 Apr 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 Comment
Kevin Bafe
Kevin Bafe on 7 Apr 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)

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!