~exist(xxx) in IF condition not working
19 ビュー (過去 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 で File Operations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!