Home > Net >  Octave: how to answer an input() prompt with a variable from my workspace?
Octave: how to answer an input() prompt with a variable from my workspace?

Time:10-16

In the command window, I define a variable var = 10. I call My_Function, and it says "Input a value: ". I want to respond " var " and have it evaluate that as 10. Is there a way to pass in the variable through input() or any other similar command?

I know how to do My_Function(var) and pass it in that way, but is there a way to take in variables at a user input prompt during the function?

CodePudding user response:

This is how the input function behaves by default, it runs the content user wrote as it is code. Make sure you are not using the 's' parameter that is commonly used to make octave interpret the input as text, instead of code.

>> var = 1;
>> x = input('Please enter the value: ')
Please enter the value: var
x = 1

Since it runs as a code, you can also do any operation here, including calling other functions.

>> x = input('Please enter the value: ')
Please enter the value: sind(30)
x = 0.5000

This works on the current workspace. If you want to reach the variables in another workspace, like the base one, you need to explicitly define that the input function should run on the base workspace.

function [] = My_Function ()
x = evalin("base","input('Please enter the value: ')");
disp(x)
endfunction


>> My_Function()
Please enter the value: var
1

CodePudding user response:

In MATLAB you can make My_Function a nested function, so all the variables in the caller workspace are visible inside the nested function. E.g.,

function Top_Function
var = 10;
result = My_Function
function x = My_Function % This is nested inside Top_Function
x = input('Input a value: ');
end
end

My_Function( ) will see all the variables in Top_Function unless they are shadowed by My_Function variables. So you can use var in the input( ) statement and it will evaluate to 10 in the above example.

  • Related