~exist(xxx) in IF condition not working
38 views (last 30 days)
Show older comments
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 Comments
Stephen23
on 26 Jun 2023
"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:
Answers (2)
Bruno Luong
on 24 Jun 2023
Moved: Bruno Luong
on 24 Jun 2023
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 Comments
Deep
on 24 Jun 2023
Edited: Deep
on 24 Jun 2023
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 Comments
See Also
Categories
Find more on Environment and Settings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!