if i use the input function to request test scores and i have three students with three test scores each. how do i make the command window spit out the total sum of each students scores with a for loop.

1 view (last 30 days)
Lk=input('input test grades for Luke : ');
La=input('input test grades for Leia: ');
An=input('input test grades for Anakin: ');
disp(sum(Lk))
disp(sum(La))
disp(sum(An))
DATA:
Luke [98 85 88]
Leia [94 90 80]
Anakin [84 78 100]
I need to use a loop so that it reads "(students name) received a total of (total points) points on the three quizzes."
  2 Comments
dpb
dpb on 2 Oct 2014
I need to use a loop so that it reads...
Then you need to use an array for the input variables instead of separately-named variables so you can address them by subscript instead of by name...
Stephen23
Stephen23 on 3 Oct 2014
Edited: Stephen23 on 3 Oct 2014
As dpb said, keep all the data values in one array, rather than in separate variables. This way of doing things makes working with MATLAB faster, neater and easier to code. You should read about indexing .

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 2 Oct 2014
To use a for loop, you'd need to store those in a container such as a structure array or cell array. So if s is your structure array, with fields name, and scores, then
s(1).name = 'Luke'
s(1).scores = [98 85 88]
s(2).name = 'Leia'
s(2).scores = [94 90 80]
s(3).name = 'Anakin'
s(3).scores = [84 78 100]
for k = 1 : length(s)
fprintf('%s received a total of %d points on the %d quizzes.\n',...
s(k).name, sum(s(k).scores), length(s(k).scores));
end

Community Treasure Hunt

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

Start Hunting!