~exist(xxx) in IF condition not working
조회 수: 61 (최근 30일)
이전 댓글 표시
I have observed a, for me strange behaviour, of MATLAB.
I setup a new workstation with a new MATLAB 2018b installation. I try to use a MATLAB script (which I use very often on my laptop without issues - same MATLAB version installed) which is crashing in an IF condition.
Condition is:
if ~exist('data')
data.data = [];
data.time = [];
end
On my laptop this code is checking the workspace for 'data'. If 'data' is existing it is doing nothing, if 'data' is not there 'data' will created with empty elements.
On the workstation with the new MATLAB installation this code is doing nothing if 'data' is not existing?!?!? It seems that the if condition is ignored.
If I use
not(exist('data'))
or
~exist('data','var')
instead of
~exist('data')
Code is working.
How could it be that same MATLAB version is reacting different on different machines? Input data (measurement file) is always the same.
I have also checked Matlab 2021b on my laptop...same behaviour...if condition is not working if 'data' is not existing...
Regards,
Timo
댓글 수: 4
Stephen23
2023년 6월 26일
"As I mentioned earlier the script is analysis measurment data and in the case a signal is not existing, 'data' will be created with empty elementss.... I have no idea why this happens."
Robust code does not mix up the paradigms of (meta-)data and code.
Robust code would not use scripts and uncontrolled magical variables popping into existence, but instead encapsulate functionality within functions or classes and pass data with specific, documented interfaces.
Robust code is more efficient:
답변 (2개)
Bruno Luong
2023년 6월 24일
이동: Bruno Luong
2023년 6월 24일
You have a FILE or FOLDER named "data" on some of your computers, not on other
exists chech existing for file and folder as well.
댓글 수: 0
Deep
2023년 6월 24일
편집: Deep
2023년 6월 24일
According to the documentation, exist can have 8 return values. It not only checks for variables in workspaces, but it can also check for other things like existing files/folders within subfolders of your current path. Even if you do not have a 'data' file/folder visible in your current folder, if its in one of the subfolders, exist() will return a non-zero value.
It may likely be a file or a folder thats being detected in your current path thats different on your laptop and your workstation.
Try using 'what' to see the folders causing this result:
what 'data'
For files, 'which' can help show files called 'data' or 'data.*' causing this result:
which 'data' -all
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Environment and Settings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!