Using while loops, to sort and index arrays.

9 次查看(过去 30 天)
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 个评论
Geoff Hayes
Geoff Hayes 2019-4-3
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.)

请先登录,再进行评论。

采纳的回答

Manuel Schmidberger
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 个评论
Kevin Bafe
Kevin Bafe 2019-4-7
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)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by