How to check if a variable exists and if yes display the variable.

조회 수: 786 (최근 30일)
Mouse
Mouse 2021년 11월 2일
댓글: Stephen23 2021년 11월 2일
clear all;
%disp(testresults); %can't work because variable testresults does not
%exist.
testresults = magic(5) %create variable
exist testresults; %returns "1", variable exists
if (exist testresults var) %why can't I check if this exists?
%File: temp.m Line: 6 Column: 11
%Invalid expression. Check for missing multiplication operator, missing or unbalanced delimiters, or other syntax error. To construct matrices, use brackets instead of parentheses.
disp(testresults);
end
why is that not possible? What should I do to fix this problem?
The variable is eventually created bevore.

답변 (2개)

Stephen23
Stephen23 2021년 11월 2일
편집: Stephen23 2021년 11월 2일
"Why can't I check if this exists?"
Of course you can, you just need to use function syntax and not command syntax:
if exist('testresults','var')
Command sytnax is a historical oddity that exists only to confuse beginners who think that certain functions must be called using command syntax, because that is what they see in the MATLAB help. In reality it can be replaced in every situation with function syntax.
"What should I do to fix this problem?"
Avoid command syntax.
  댓글 수: 2
Steven Lord
Steven Lord 2021년 11월 2일
There are situations where command form is more natural IMO.
help plot % vs help('plot')
doc fft % doc('fft')
hold on % hold('on')
quit force % quit('force')
clear all % clear('all')
close all % close('all')
Stephen23
Stephen23 2021년 11월 2일
@Steven Lord: yes to HELP, QUIT, and DOC when called from the command window.
No to HOLD: without explicit object handles such a GUI is too fragile for my taste.

댓글을 달려면 로그인하십시오.


Image Analyst
Image Analyst 2021년 11월 2일
Try this
try
testresults % Spew results to command window.
catch ME
message = sprintf('Note: testresults is not a variable in scope.');
uiwait(warndlg(message))
end

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by