~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!