How to create a matrix out of single inputs in a loop?
조회 수: 1 (최근 30일)
이전 댓글 표시
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
답변 (3개)
Andy
2011년 5월 13일
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
Laura Proctor
2011년 5월 13일
Just change the line that defines B to this:
B(a)=input('Enter the grades: ');
This will result in a vector for B.
댓글 수: 1
Andy
2011년 5월 13일
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Web Services에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!