How to make a variable in one .m file make changes in another .m file?
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Image Analyst
2012-1-16
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 个评论
更多回答(1 个)
Jan
2012-1-16
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 个评论
Walter Roberson
2012-1-16
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 .
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Install Products 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!