how to do a command line only if it is possible?

Dear all, sorry for the "stupid" question. I am writing a code and sometimes happens that i want to recall a previous setting only if it exists, so i am using try as following
try setting=previous_setting; catch end
in this way if the previous setting exists it will used, if not nothing happens. Now i think that using try and catch is not so nice since it should be used for error tracing. Do you have any advice (i would not like to use if)? thank you all catch end
in this way if the previous setting exists it will used, if not nothing happens. Now i think that using try and catch is not so nice since it should be used for error tracing. Do you have any advice (i would not like to use if)? thank you all

 Accepted Answer

if exist('previous_setting')
end
If previous_setting is variable, use
exist('previous_setting', 1)
if it is an m-file, use
exist('previous_setting', h)
See
help exist
for further options.

3 Comments

While this is a good answer (that I up-voted) there is no reason why try/catch is not acceptable. In fact, you may find that it is actually more efficient than a test for existence.
The best thing to do, is to test it out. So, here I've written a simple function to compare times.
function testfun()
%{
try
setting=previous_setting;
catch
setting = 17;
end
%}
if ~exist('previous_setting','var')
setting = 17;
end
In my first test, I block commented the exist call out, using the try/catch construct.
timeit(@() testfun)
ans =
0.0010885090595
Then I swapped the block comments, so using the exist test.
timeit(@() testfun)
ans =
1.32021526428571e-05
So exist was faster, nearly by a factor of 100-1. But it is always a good idea to test these things.
thank you for the answer. i would use the lowest number of strings in the code (this is why i dont want to use if). So if according to you there is no error to use try w/o catch i will proceed like that.
As I pointed out in the test though, exist is faster. If this is a question of milliseconds, it may not matter. Much time is spent by programmers looking for an optimal solution, when the cost is only a few milliseconds. Of course, if the code will be executed thousands or millions of times you should worry about the difference. But for something that will happen once, even one second of programmer time spent on the choice is a net waste of time.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!