MATLAB Answers

0

How to create a matrix out of single inputs in a loop?

Asked by Abdullah on 13 May 2011
I'm a first year Engineering student, Currently sitting down to solve basic problems by MATLAB. Anyway, I have a problem that I couldn't figure out how to solve.
This problem requires to create a for loop that allows the user to enter the number of students. Each student should be assigned to a grade in another variable, let's assume it's called B. The question is, in this case, how can I make a matrix out of the variable B? The goal of creating B as a matrix is to be able to do some calculations, like calculating the biggest grade, and the average of the grades?
I started like this:
n=input('Enter the number of the student: '); for a=1:n B=input('Enter the grades: '); end
I want the grades in variable B to be assigned into a matrix rather than single values? How can this be done?
Thanks in advance.

  0 Comments

Sign in to comment.

3 Answers

Answer by Andy
on 13 May 2011

If your grades are entered as strings, you should store them in a cell array:
numStudents = 20; % or however many
B = cell(numStudents,1);
for a = 1:numStudents
B{a} = input('Enter the grade for the next student: ', 's');
end
You can then do your analysis using the cell array B, or you can convert letter grades to numbers (via a 4 point scale or however you'd like) so that you can do analysis using the numeric grades.
Note: use the 's' option for input. By default, input EVALUATES the input expression. It does not simply return the string. I would imagine this is not your intended result.

  0 Comments

Sign in to comment.


Answer by Laura Proctor on 13 May 2011

Just change the line that defines B to this:
B(a)=input('Enter the grades: ');
This will result in a vector for B.

  1 Comment

By using parentheses (i.e., 'B(a)') rather than curly braces (i.e., 'B{a}'), you have created a string rather than a cell array (assuming the assigned grades are letter grades). Moreover, if grades such as B+ and A- are involved, the length of the resulting string will not be the same as the number of students. So to do analysis, you will need to parse the string rather than simply loop over it.

Sign in to comment.


Answer by Abdullah on 13 May 2011

Thank you for your very fast responses!
Just to clarify more things, the grades are entered as numerical values, not as strings. Although before I asked this question, I did what Laura Proctor has suggested to do, Variable B wasn't made as a matrix, but I just have done it again, and it has worked, variable B is now a matrix.
Thanks you again. This question is now solved.

  0 Comments

Sign in to comment.