Trying to have user input names into matlab and store them in a matrix

10 ビュー (過去 30 日間)
Christian Ressler
Christian Ressler 2019 年 12 月 6 日
編集済み: dpb 2019 年 12 月 6 日
I am working on a project where I can input names and have them stored in a matrix or vector, but keep getting this error.
"Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.
Error in Cy_Young_Program (line 4)
pitcher_prompt(pn) = input('Input Pitcher Name: ',"s")"
Here is the code I am using...
injury_prob = rand;
%Code for inputing different pitchers names
for pn = 1:3
pitcher_prompt(pn) = input('Input Pitcher Name: ',"s")
%ppm()
end
Capture.JPG

回答 (1 件)

dpb
dpb 2019 年 12 月 6 日
編集済み: dpb 2019 年 12 月 6 日
Don't use the character array...assignment in it has to be padded to the maximum length for every row in the array. Either use a cell array, or probably better assuming you have recent release of Matlab is the new(ish) string class.
Actually, my release (R2017b) errors on the "s" second argument and I don't see that it's allowed by the current online documentation, either. Maybe the new release does allow it and the documentation wasn't updated?
>> n=input('Name ',"s")
Error using input
The second argument to INPUT must be 's'.
>>
>> n=input('Name: ','s')
Name: Fred Flintstone
n =
'Fred Flintstone'
>> whos n
Name Size Bytes Class Attributes
n 1x15 30 char
>>
As you see, input returns a char() array.
Use
>> clear n
>> n(1)=string(input('Name: ','s'))
Name: Fred Flintstone
n =
"Fred Flintstone"
>> n(2)=string(input('Name: ','s'))
Name: Barney Rubble
n =
1×2 string array
"Fred Flintstone" "Barney Rubble"
>> clear n
>> n(1)={input('Name: ','s')}
Name: Jimmy Dean
n =
1×1 cell array
{'Jimmy Dean'}
>> n(2)={input('Name: ','s')}
Name: Johnson Bratwurst
n =
1×2 cell array
{'Jimmy Dean'} {'Johnson Bratwurst'}
>>
your choice as to whether to use the string array or a cell array; I would recommend the string as better choice. You probably will want to arrange as a column array rather than the default row as above, that just illustrated the syntax to use.

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by