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

1 visualización (últimos 30 días)
Abdullah
Abdullah el 13 de Mayo de 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.

Respuestas (3)

Andy
Andy el 13 de Mayo de 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.

Laura Proctor
Laura Proctor el 13 de Mayo de 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 comentario
Andy
Andy el 13 de Mayo de 2011
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.

Iniciar sesión para comentar.


Abdullah
Abdullah el 13 de Mayo de 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.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by