I need help with basic input/output commands in a script file
3 次查看(过去 30 天)
显示 更早的评论
My problem reads this:
Write a MATLAB program in a script file that calculate the average, standard deviation, and median of a list of grades as well as the number of grades on the list. The program asks the user (input command) to enter the grades as elements of a vector. The program then calculates the required quantities using MATLAB’s built-in functions length, mean, std, and median. The results are displayed in the Command Window in the following format:
- “There are XX grades.” where XX is the numerical value.
- “The average grade is XX.” where XX is the numerical value.
- “The standard deviation is XX.” where XX is the numerical value.
- “The median deviation is XX.” where XX is the numerical value.
Execute the program and enter the following grades: 81, 65, 61, 78, 94, 80, 65, 76, 77, 95, 82, 49, and 75.
What I'm getting from this in the command window does not make sense... it looks like this: (after running the script file)
Enter grades: 81 65 61 78 94 80 65 76 77 95 82 49 75
There are 38 grades.
The average grade is 46.89.
The standard deviation is 10.46.
The median deviation is 53.00.EDU>>
Now I know there obviously aren't 38 grades, and the others are wrong as well. I've tried several different ways and have read up on everything in the tutorial, manual, and online and can't find what I'm doing wrong. Any help on this is appreciated. Thanks!
0 个评论
采纳的回答
Walter Roberson
2013-3-3
You are reading the grades as a string, but then you are treating the string as if were a vector of numbers. Either read the grades as a number (no 's' option) or convert the string to numeric.
4 个评论
Walter Roberson
2013-3-4
Whatever happened to testing?
>> S=input('Enter grades: ')
Enter grades: 1 5 9 17
1 5 9 17
|
Error: Unexpected MATLAB expression.
>> S=input('Enter grades: ')
Enter grades: 1,5,9,17
Error: Unexpected MATLAB expression.
Enter grades: [1 5 9 17]
S =
1 5 9 17
If you want the user to be able to enter them without the [] then input a string and convert it.
>> str2double(regexp('1 5 9 17','\s+','split'))
ans =
1 5 9 17
>> sscanf('1 5 9 17', '%f')
ans =
1
5
9
17
>> str2num('1 5 9 17')
ans =
1 5 9 17
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!