How to make a variable in one .m file make changes in another .m file?
6 views (last 30 days)
Show older comments
Hi, I change the variable of one .m file and want that this number be automatically rewritten for another variable in another .m file.
For example, I open the file:
open cpcorr.m;
and change the value in line 76 as below:
CORRSIZE = 4;
Now I have a new newfile.m with the variable
CS=CORRSIZE;
Thus, when I change the value of CORRSIZE in cpcorr.m, I wish also that the value of CS in file1.m be automatically changed, for this particular example, CS would equal 4.
I hope someone knows how to fix this.
Thanks in advance for your help
Emerson
1 Comment
Accepted Answer
Image Analyst
on 16 Jan 2012
You can't do it if all you do is to change the text in the m-file. After all, an m-file is stored simply as a flat text file on disk. One text file sitting there on disk is not going to know that it needs to change itself if some other file somewhere on disk changed itself. However if you run the m-file, then you can put code in it to change the variable value in the other m-file. Look at the assignin() function.
0 Comments
More Answers (1)
Jan
on 16 Jan 2012
There is way to let M-files interact magically.
If you want to share the definition of a variable, create a dedicated function for defining the values:
function Value = ShareData(Name)
switch Name
case 'CORRSIZE'
Value = 4;
case 'AnotherVariable'
Value = 1:17;
otherwise
error(['Tools:', mfilename, ':UnknownName'], ...
'Unknown name: %s', Name);
end
Now all functions, which need the same value for a specific variable can use:
CS = ShareData('CORRSIZE');
This is a programmatical way to create "global" data. Another method would be to use the global statement of Matlab. But this is less secure, because then the value can be modified from anywhere, while the ShareData-function approach ensures, that there is only one location, where the values are defined.
2 Comments
Walter Roberson
on 16 Jan 2012
cpcorr.m is not a valid variable name that can appear as the name of a dummy argument to a function(). In the dummy argument to a function, variable names must be simple names with no '.' and no indexing .
See Also
Categories
Find more on Install Products in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!