필터 지우기
필터 지우기

Using while loops, to sort and index arrays.

조회 수: 9 (최근 30일)
Kevin Bafe
Kevin Bafe 2019년 4월 3일
댓글: Kevin Bafe 2019년 4월 7일
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
Manuel Schmidberger 2019년 4월 5일
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