Using an existing vector in a .M file
Show older comments
Hello! I've made a simple function file and let's say I need to input a vector (50 elements) so that a function gives me the resulting vector for those elements. I have the vector in the workspace but when I try to use it as an input (instead of for example introducing the input like this [1 2 3 4 5... 50]) the vector is not recognised as a valid entry and is as if i hadn't introduced nothing. How could I solve this? Is a problem in the script? I have it as:
P_k='Introduce the 50 values';
P_k=input(P_K);
I'm new into this and I really don't know how can I solve this and hadn't found anything related
8 Comments
Eduardo Chacin
on 31 Aug 2018
Edited: Stephen23
on 31 Aug 2018
Eduardo Chacin
on 31 Aug 2018
@Eduardo Chacin: change the function to accept input arguments.
For some reason some beginners think that forcing the user to enter everything with input is the best thing since sliced bread. But, as you are finding out now, this just slowly and pointlessly forces the user to interact with the function in just one way: through whatever input prompts they happen throw at the user. This means that it is not possible to call the function efficiently in a loop with different input values, or use it in any optimizing function, or really do anything useful with it at all. In short, input is how some beginners make their functions totally impractical to work with.
The solution is that you should edit that function, get rid of any input commands and replace them with function input arguments, exactly as described in the function help. Then just call the function with the input values that you require. Exactly as all functions should be!
Eduardo Chacin
on 31 Aug 2018
function C = myFun(A,B)
C = A + B;
end
Then call the function with the required inputs:
myFun(pi,0:10)
Eduardo Chacin
on 31 Aug 2018
Answers (1)
M
on 31 Aug 2018
0 votes
Does this discussion https://mathworks.com/matlabcentral/answers/1748-storing-user-input-as-a-vector answer your question ?
1 Comment
Eduardo Chacin
on 31 Aug 2018
Categories
Find more on Performance and Memory in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!