How can I get matlab to execute one or both parts of a code depending on whether a variable exists?
조회 수: 2 (최근 30일)
이전 댓글 표시
I want to define a cell of data from a particular file if that particular file exists and a different cell of data if a different file exists. Sometimes both files will exist and sometimes only one. I then want to perform some operations on the cell(s) that exist, but a different operation on each existing file. I.e. I might have cell1 and cell2 or I might just have cell1 or just cell2. There will be a set of operations to perform if cell1 exists and a different set of operations to perform if cell2 exists, and if both exist I want to perform both sets of operations. What sort of structure would be best to do this?
댓글 수: 0
채택된 답변
Stephen23
2019년 3월 4일
편집: Stephen23
2019년 3월 4일
Avoid checking if variables exist or not (such introspective programming is a path to slow, complex, spaghetti code which is difficult to debug). The clearest code would explicitly indicate if that data has been loaded or not, for which a simple cell array or structure is quite sufficient:
S = struct('data',{[],[]},'loaded',{false,false})
...
S(1).data = ... optionally import file one.
S(1).loaded = true;
...
S(2).data = ... optionally import file two.
S(2).loaded = true;
...
if S(2).loaded % check if file two data has been loaded
S(2).data % do something ...
end
[S.loaded] % check if all files have been loaded
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!