how to share data between different m files

조회 수: 2 (최근 30일)
Habib Khan
Habib Khan 2016년 8월 17일
편집: Stephen23 2016년 8월 17일
I have three m files using the same variables and carrying out calculations on these variables. I have made one m file in which i have declared all the variables and I can share the variables to different m files using their names. My problem is that the variable names change too often and then I have to change the variable names in all these files. I want some methodology so that I can change the variable name and value and these changed names are still linked to other m files of the project.

답변 (2개)

Stephen23
Stephen23 2016년 8월 17일
편집: Stephen23 2016년 8월 17일
This is easy:
  1. make sure that you only write functions (not scripts).
  2. pass the variables as arguments.
It does not matter what names variables have inside your functions because these are completely invisible to the outside world, so you never need to change them again. Note that although beginners love using scripts, they are really just for playing around, and you will have to learn how to write, debug, and work with functions one day if you wish to write robust, reliable code.
If you have lots of variables, put them into a structure rather than passing them around individually. If you need to select variables from a set, range or something similar then simply learn to use vectors and indexing: do NOT select them by changing their names!
Note that each function has its own workspace: you need to learn that this is a good thing, and do not try to fight it by trying to share all variables, or doing something awful like using global.
  댓글 수: 2
Habib Khan
Habib Khan 2016년 8월 17일
@Stephen. When I use the functions, the names of the variables inside functions will change as well. But I want to preserve the names in all m files, hence functions may not be suitable for me.
Stephen23
Stephen23 2016년 8월 17일
편집: Stephen23 2016년 8월 17일
@Habib Khan: as I already said in my answer, instead of changing variables names you could simply use indexing, then this entire problem will be resolved. In some rare cases it might be necessary to use dynamic field names with a structure, but in no normal code is it required to change variable names within a function.
Changing variables names inside a function makes no sense: it defeats the purpose of a function, which is to have its own independent workspace. The names of variables inside that workspace should not matter.

댓글을 달려면 로그인하십시오.


Thorsten
Thorsten 2016년 8월 17일
I would write a three functions, as Stephen suggested. But if you insist that all variables need to have the same name in all four files, you have to edit the four files accordingly.

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by