Adding to an array within a For loop?

조회 수: 1 (최근 30일)
Caroline Culver
Caroline Culver 2020년 9월 24일
답변: David Hill 2020년 9월 24일
%%I am trying to add a student's number to the gpa4 and class_honors lists if they meet my if statement conditionals but my output still shows them as empty arrays
rng('default')
data(:,1) = randperm(300); %student number
data(:,2) = randi(4,300,1) + 14; %class year
data(:,3) = randi(20,300,1)/10 + 2; %gpa
checkvalues = mean(data);
gpa4 = [];
class_honors = [];
class_psych = 0;
ctr = 1;
for i = 1:300
if data(i,3) == 4.0
gpa4 = gpa4 + data(i,1);
end
if (data(i,2) == 2015) & (data(i,3) >= 3.5)
class_honors = class_honors + data(i,1);
end
if (data(i,2) == 2018) & (data(i,3) >= 3.0)
class_psych + 1;
end
end
disp('Students with a 4.0:')
disp(gpa4)
disp('Seniors with honors:')
disp(class_honors)
disp('# of first year potential psychology majors:')
disp(class_psych)
student_one = data(1,3);
disp('Student One GPA:')
disp(student_one)
class_17 = std(data(:,2));
disp('Class of 17 GPA Standard Deviation:')
disp(class_17)
  댓글 수: 1
Caroline Culver
Caroline Culver 2020년 9월 24일
my output currently looks like this:
Students with a 4.0:
Seniors with honors:
# of first year potential psychology majors:
0
Student One GPA:
3.8000
Class of 17 GPA Standard Deviation:
1.0638

댓글을 달려면 로그인하십시오.

답변 (1개)

David Hill
David Hill 2020년 9월 24일
No loop needed.
gpa4=nnz(data(:,3) == 4);
class_honors=nnz(data(:,2) == 2015 & data(:,3) >= 3.5);
class_psych=nnz(data(:,2) == 2018 & data(:,3) >= 3.0);

카테고리

Help CenterFile Exchange에서 Eigenvalue Problems에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by