Changing a variable which is inside a function file from a script

4 views (last 30 days)
Hi everyone:
I have a question. The question is that is there a way to change a value which is defined inside a function file from a script file.
For example:
I have a function .m file called A, and this function file outputs a struct.
Inside this A.m file, I have defined a value x= 5 which is inside a struct along with other variables.
This function A.m file will then will called by a s-function to do some calculation. However, before being called by the s-function, I want to change the value x to another value from a script file B.m, so that the modified A.m function file can then be used in the s-function to obtain a different result.
Is there a way to do it?
I have tried loading all the variables (the struct) to the workspace and change the value of x, but this change only happened in the workspace but not in the function A .m file. Is there a way to make the change directly in the function file?
Thank you very much
Tommy

Accepted Answer

Dishant Arora
Dishant Arora on 29 Mar 2014
make use of global or evalin, but it's suggested to avoid both of them. You might want to make use of setappdata and getappdata.
setappdata(0,'Variable',x) % In your script file.
x = getappdata(0,'Variable') % In function file.
  3 Comments
Dishant Arora
Dishant Arora on 29 Mar 2014
A = 1:10;
A(4:1) % See what MATLAB says
In your loop same thing happens, your starting indices is greater than end indices. Do this:
b(i:-1:1) % Instead of b(i:1)
Or perhaps you want:
b(1:i)
Tommy
Tommy on 29 Mar 2014
Hi Dishant
Thank you very much for your help.
I have sorted out the problem I had. I made a very stupid mistake. I should have b(i,1) instead of b(i:1).
Thank you very much for your help
Tommy

Sign in to comment.

More Answers (1)

erick oibi
erick oibi on 4 May 2018
Hey, I have 5 functions and one script. I want to update data in one of the functions, to be used in function two, when function two is called in the script. this is the first function: busdatas.m. The second function is loadflow.m. loadflow function, uses data from function busdatas.m and other functions to do loadflow. in my script, named: indexing, I want to update databus.m data before using it in load flow. The data is not changed when carrying out loadflow, it changes only in the script when displaying. Kindly help me update the data line 38 of the script named indexing. I have tried to use setappdata and getappdata functions, but I am getting it wrong, Kindly help me.

Products

Community Treasure Hunt

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

Start Hunting!