Undocumented Matlab
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT

Interesting Matlab puzzle – analysis

April 9, 2019 One Comment

Last week I presented a seemingly-innocent Matlab code snippet with several variants, and asked readers to speculate what its outcomes are, and why. Several readers were apparently surprised by the results. In today’s post, I offer my analysis of the puzzle.
The original code snippet was this:

function test
    try
        if (false) or (true)            disp('Yaba');
        else
            disp('Daba');
        end
    catch
        disp('Doo!');
    end
end

function test try if (false) or (true) disp('Yaba'); else disp('Daba'); end catch disp('Doo!'); end end

With the following variants for the highlighted line #3:

        if (false) or (true)     % variant #1 (original)
        if (true)  or (false)    % variant #2
        if (true)  or (10< 9.9)  % variant #3
        if  true   or  10< 9.9   % variant #4
        if 10> 9.9 or  10< 9.9   % variant #5

if (false) or (true) % variant #1 (original) if (true) or (false) % variant #2 if (true) or (10< 9.9) % variant #3 if true or 10< 9.9 % variant #4 if 10> 9.9 or 10< 9.9 % variant #5

Variant #1: if (false) or (true)

The first thing to note is that or is a function and not an operator, unlike some other programming languages. Since this function immediately follows a condition (true), it is not considered a condition by its own, and is not parsed as a part of the “if” expression.
In other words, as Roger Watt correctly stated, line #3 is actually composed of two separate expressions: if (false) and or(true). The code snippet can be represented in a more readable format as follows, where the executed lines are highlighted:

        if (false)            or (true)
            disp('Yaba');
        else
            disp('Daba');        end

if (false) or (true) disp('Yaba'); else disp('Daba'); end

Since the condition (false) is never true, the “if” branch of the condition is never executed; only the “else” branch is executed, displaying ‘Daba’ in the Matlab console. There is no parsing (syntactic) error so the code can run, and no run-time error so the “catch” block is never executed.
Also note that despite the misleading appearance of line #3 in the original code snippet, the condition only contains a single condition (false) and therefore neither short-circuit evaluation nor eager evaluation are relevant (they only come into play in expressions that contain 2+ conditions).
As Rik Wisselink speculated and Michelle Hirsch later confirmed, Matlab supports placing an expression immediately following an “if” statement, on the same line, without needing to separate the statements with a new line or even a comma (although this is suggested by the Editor’s Mlint/Code-Analyzer). As Michelle mentioned, this is mainly to support backward-compatibility with old Matlab code, and is a discouraged programming practice. Over the years Matlab has made a gradual shift from being a very weakly-typed and loose-format language to a more strongly-typed one having stricter syntax. So I would not be surprised if one day in the future Matlab would prevent such same-line conditional statements, and force a new line or comma separator between the condition statement and the conditional branch statement.
Note that the “if” conditional branch never executes, and in fact it is optimized away by the interpreter. Therefore, it does not matter that the “or” function call would have errored, since it is never evaluated.

Variant #2: if (true) or (false)

In this variant, the “if” condition is always true, causing the top conditional branch to execute. This starts with a call to or(false), which throws a run-time error because the or() function expects 2 input arguments and only one is supplied (as Chris Luengo was the first to note). Therefore, execution jumps to the “catch” block and ‘Doo!’ is displayed in the Matlab console.
In a more verbose manner, this is the code (executed lines highlighted):

function test
    try
        if (true)            or (false)            disp('Yaba');
        else
            disp('Daba');
        end
    catch
        disp('Doo!');    end
end

function test try if (true) or (false) disp('Yaba'); else disp('Daba'); end catch disp('Doo!'); end end

Variant #3: if (true) or (10< 9.9)

This is exactly the same as variant #2, since the condition 10< 9.9 is the same as false. The parentheses around the condition ensure that it is treated as a single logical expression (that evaluates to false) rather than being treated as 2 separate arguments. Since the or() function expects 2 input args, a run-time error will be thrown, resulting in a display of ‘Doo!’ in the Matlab console.
As Will correctly noted, this variant is simply a red herring whose aim was to lead up to the following variant:

Variant #4: if true or 10< 9.9

At first glance, this variant looks exactly the same as variant #3, because parentheses around conditions are not mandatory in Matlab. In fact, if a || b is equivalent to (and in many cases more readable/maintainable than) if (a) || (b). However, remember that “or” is not a logical operator but rather a function call (see variant #1 above). For this reason, the if true or 10< 9.9 statement is equivalent to the following:

        if true
            or 10< 9.9
            ...

if true or 10< 9.9 ...

Now, you might think that this will cause a run-time error just as before (variant #2), but take a closer look at the input to the or() function call: there are no parentheses and so the Matlab interpreter parses the rest of the line as space-separated command-line inputs to the or() function, which are parsed as strings. Therefore, the statement is in fact interpreted as follows:

        if true
            or('10<', '9.9')
            ...

if true or('10<', '9.9') ...

This is a valid “or” statement that causes no run-time error, since the function receives 2 input arguments that happen to be 3-by-1 character arrays. 3 element-wise or are performed ('1'||'9' and so-on), based on the inputs’ ASCII codes. So, the code is basically the same as:

        if true
            or([49,48,60], [57,46,57])  % =ASCII values of '10<','9.9'
            disp('Yaba');

if true or([49,48,60], [57,46,57]) % =ASCII values of '10<','9.9' disp('Yaba');

Which results in the following output in the Matlab console:

ans =
  1×3 logical array
   1   1   1
Yaba

ans = 1×3 logical array 1 1 1 Yaba

As Will noted, this variant was cunningly crafted so that the 2 input args to “or” would each have exactly the same number of chars, otherwise a run-time error would occur (“Matrix dimensions must agree”, except for the edge case where one of the operands only has a single element). As Marshall noted, Matlab syntax highlighting (in the Matlab console or editor) can aid us understand the parsing, by highlighting the or() inputs in purple color, indicating strings.

Variant #5: if 10> 9.9 or 10< 9.9

This is another variant whose main aim is confusing the readers (sorry about that; well, not really…). This variant is exactly the same as variant #4, because (as noted above) Matlab conditions do not need to be enclosed by parentheses. But whereas 10> 9.9 is a single scalar condition (that evaluates to true), 10< 9.9 are in fact 2 separate 3-character string arguments to the “or” function. The end result is exactly the same as in variant #4.
I hope you enjoyed this little puzzle. Back to serious business in the next post!

USA visit

I will be travelling in the US (Boston, New York, Baltimore) in May/June 2019. Please let me know (altmany at gmail) if you would like to schedule a meeting or onsite visit for consulting/training, or perhaps just to explore the possibility of my professional assistance to your Matlab programming needs.

Related posts:

  1. Interesting Matlab puzzle – A simple Matlab puzzle that leads to interesting insight on Matlab's parser. ...
  2. An interesting uitree utility – ExploreStruct is a utility that shows how custom uitrees can be integrated in Matlab GUI...
  3. A couple of internal Matlab bugs and workarounds – A couple of undocumented Matlab bugs have simple workarounds. ...
  4. Matlab and the Event Dispatch Thread (EDT) – The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....
  5. Runtime code instrumentation – Conditional breakpoints can be used to instrument code with user-specified code. ...
  6. Blurred Matlab figure window – Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...
Pure Matlab Undocumented feature
Print Print
« Previous
Next »
One Response
  1. Mr Ashley Trowell November 12, 2020 at 19:32 Reply

    Thank you so much for this analysis.
    Also, I find it somewhat horrifying.

    The take away seems to be to use && / || and NOT and / or.
    Thanks a bunch!

    ~Ashley

Leave a Reply
HTML tags such as <b> or <i> are accepted.
Wrap code fragments inside <pre lang="matlab"> tags, like this:
<pre lang="matlab">
a = magic(3);
disp(sum(a))
</pre>
I reserve the right to edit/delete comments (read the site policies).
Not all comments will be answered. You can always email me (altmany at gmail) for private consulting.

Click here to cancel reply.

Useful links
  •  Email Yair Altman
  •  Subscribe to new posts (feed)
  •  Subscribe to new posts (reader)
  •  Subscribe to comments (feed)
 
Accelerating MATLAB Performance book
Recent Posts

Speeding-up builtin Matlab functions – part 3

Improving graphics interactivity

Interesting Matlab puzzle – analysis

Interesting Matlab puzzle

Undocumented plot marker types

Matlab toolstrip – part 9 (popup figures)

Matlab toolstrip – part 8 (galleries)

Matlab toolstrip – part 7 (selection controls)

Matlab toolstrip – part 6 (complex controls)

Matlab toolstrip – part 5 (icons)

Matlab toolstrip – part 4 (control customization)

Reverting axes controls in figure toolbar

Matlab toolstrip – part 3 (basic customization)

Matlab toolstrip – part 2 (ToolGroup App)

Matlab toolstrip – part 1

Categories
  • Desktop (45)
  • Figure window (59)
  • Guest bloggers (65)
  • GUI (165)
  • Handle graphics (84)
  • Hidden property (42)
  • Icons (15)
  • Java (174)
  • Listeners (22)
  • Memory (16)
  • Mex (13)
  • Presumed future risk (394)
    • High risk of breaking in future versions (100)
    • Low risk of breaking in future versions (160)
    • Medium risk of breaking in future versions (136)
  • Public presentation (6)
  • Semi-documented feature (10)
  • Semi-documented function (35)
  • Stock Matlab function (140)
  • Toolbox (10)
  • UI controls (52)
  • Uncategorized (13)
  • Undocumented feature (217)
  • Undocumented function (37)
Tags
ActiveX (6) AppDesigner (9) Callbacks (31) Compiler (10) Desktop (38) Donn Shull (10) Editor (8) Figure (19) FindJObj (27) GUI (141) GUIDE (8) Handle graphics (78) HG2 (34) Hidden property (51) HTML (26) Icons (9) Internal component (39) Java (178) JavaFrame (20) JIDE (19) JMI (8) Listener (17) Malcolm Lidierth (8) MCOS (11) Memory (13) Menubar (9) Mex (14) Optical illusion (11) Performance (78) Profiler (9) Pure Matlab (187) schema (7) schema.class (8) schema.prop (18) Semi-documented feature (6) Semi-documented function (33) Toolbar (14) Toolstrip (13) uicontrol (37) uifigure (8) UIInspect (12) uitools (20) Undocumented feature (187) Undocumented function (37) Undocumented property (20)
Recent Comments
  • Nicholas (6 days 22 hours ago): Hi Yair, Thanks for the reply. I am on Windows 10. I also forgot to mention that this all works wonderfully out of the editor. It only fails once compiled. So, yes, I have tried a...
  • Nicholas (6 days 22 hours ago): Hi Yair, Thanks for the reply. I am on Windows 10. I also forgot to mention that this all works wonderfully out of the editor. It only fails once compiled. So, yes, I have tried a...
  • Yair Altman (7 days 5 hours ago): Nicholas – yes, I used it in a compiled Windows app using R2022b (no update). You didn’t specify the Matlab code location that threw the error so I can’t help...
  • Nicholas (8 days 1 hour ago): Hi Yair, Have you attempted your displayWebPage utility (or the LightweightHelpPanel in general) within a compiled application? It appears to fail in apps derived from both R2022b...
  • João Neves (11 days 6 hours ago): I am on matlab 2021a, this still works: url = struct(struct(struct(struct(hF ig).Controller).PlatformHost). CEF).URL; but the html document is empty. Is there still a way to do...
  • Yair Altman (14 days 4 hours ago): Perhaps the class() function could assist you. Or maybe just wrap different access methods in a try-catch so that if one method fails you could access the data using another...
  • Jeroen Boschma (14 days 7 hours ago): Never mind, the new UI components have an HTML panel available. Works for me…
  • Alexandre (14 days 8 hours ago): Hi, Is there a way to test if data dictionnatry entry are signal, simulink parameters, variables … I need to access their value, but the access method depends on the data...
  • Nicholas (14 days 22 hours ago): In case anyone is looking for more info on the toolbar: I ran into some problems creating a toolbar with the lightweight panel. Previously, the Browser Panel had an addToolbar...
  • Jeroen Boschma (18 days 5 hours ago): I do not seem to get the scrollbars (horizontal…) working in Matlab 2020b. Snippets of init-code (all based on Yair’s snippets on this site) handles.text_explorer...
  • Yair Altman (46 days 7 hours ago): m_map is a mapping tool, not even created by MathWorks and not part of the basic Matlab system. I have no idea why you think that the customizations to the builtin bar function...
  • chengji chen (46 days 14 hours ago): Hi, I have tried the method, but it didn’t work. I plot figure by m_map toolbox, the xticklabel will add to the yticklabel at the left-down corner, so I want to move down...
  • Yair Altman (54 days 7 hours ago): @Alexander – this is correct. Matlab stopped including sqlite4java in R2021b (it was still included in 21a). You can download the open-source sqlite4java project from...
  • Alexander Eder (60 days 2 hours ago): Unfortunately Matlab stopped shipping sqlite4java starting with R2021(b?)
  • K (66 days 13 hours ago): Is there a way to programmatically manage which figure gets placed where? Let’s say I have 5 figures docked, and I split it into 2 x 1, I want to place 3 specific figures on the...
Contact us
Captcha image for Custom Contact Forms plugin. You must type the numbers shown in the image
Undocumented Matlab © 2009 - Yair Altman
This website and Octahedron Ltd. are not affiliated with The MathWorks Inc.; MATLAB® is a registered trademark of The MathWorks Inc.
Scroll to top