MATLAB Answers

Adding to an array within a For loop?

10 views (last 30 days)
Caroline Culver
Caroline Culver on 24 Sep 2020 at 16:48
Answered: David Hill on 24 Sep 2020 at 17:01
%%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 Comment

Caroline Culver
Caroline Culver on 24 Sep 2020 at 16:49
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

Sign in to comment.

Answers (1)

David Hill
David Hill on 24 Sep 2020 at 17:01
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);

  0 Comments

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!