input and arrays
I want to know how to store input values 开发者_如何学Pythonin an array in MATLAB by asking the question only one time, like this output
Enter values for mass (mo): [1 2 3 4 5]
The default behavior of INPUT will allow you to enter a vector, provided you include the square brackets when typing your input:
>> vec = input('Enter values for mass (mo): '); %# Ask for input
Enter values for mass (mo): [1 2 3 4 5] %# Enter [1 2 3 4 5]
>> vec %# Display vec
vec =
1 2 3 4 5
This behavior may not be obvious, as you may be used to entering only scalar values and strings with INPUT. You have to pay special attention to this part of the documentation (emphasis added):
evalResponse = input(prompt)
displays theprompt
string on the screen, waits for input from the keyboard, evaluates any expressions in the input, and returns the value inevalResponse
. To evaluate expressions, theinput
function accesses variables in the current workspace.
This means you could even enter input like this:
Enter values for mass (mo): [1*8 2+9 zeros(1,3) pi]
>> vec
vec =
8.0000 11.0000 0 0 0 3.1416
gnovice's & Peter R.'s answers address your question. However, I thought I'd mention why using evaluated responses for applications where where you're not the end user is a terrible idea.
While the feature is certainly useful, as demonstrated by gnovice, it also evaluates system calls!
Enter values for mass: system('echo "hello world" ')
hello world
That's a response from my OS. vec
just stores the exit return value from the function. You can pretty much do anything, including
Enter values for mass: system('rm -rf /')
which will simply erase the entire drive, if running as super user. Granting users an entry to your OS is simply a bad, bad idea, and I mention this, because I've seen several science kiosks, where they have some small program written in MATLAB to illustrate some concept and and use input
to request values from the users (random folks strolling by). Perhaps not everyone thinks like me, so they haven't had trouble so far :). However, this is just like SQL injections and every argument that can be made for sanitizing databases, can be applied here too.
The way around in this case, is to use input
with an optional second input argument, as
vec=input('Enter values for mass: ','s');
This stores the unevaluated string to the variable vec
, and you can then check for malicious content before evaluating it (or only allow a whitelisted set of functions & characters).
Enter values for mass: system('echo "hello world" ')
>> vec
vec =
system('echo "hello world" ')
myArray = input(‘Enter values for mass (mo): ’);
精彩评论