Quantcast
Channel: Undocumented Matlab
Viewing all articles
Browse latest Browse all 111

Interesting Matlab puzzle

$
0
0

Here’s a nice little puzzle that came to me from long-time Matlab veteran Andrew Janke:

Without actually running the following code in Matlab, what do you expect its output to be? ‘Yaba’? ‘Daba’? perhaps ‘Doo!’? or maybe it won’t run at all because of a parsing error?

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

To muddy the waters a bit, do you think that short-circuit evaluation is at work here? or perhaps eager evaluation? or perhaps neither?
Would the results be different if we switched the order of the conditional operands, i.e. (true) or (false) instead of (false) or (true)? if so, how and why?
And does it matter if I used “false” or “10< 9.9” as the “or” conditional?
Are the parentheses around the conditions important? would the results be any different without these parentheses?

In other words, how and why would the results change for the following variants?

        if (false) or (true)     % variant #1
        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

Please post your thoughts in a comment below (expected results and the reason, for the main code snippet above and its variants), and then run the code. You might be surprised at the results, but not less importantly at the reasons. This deceivingly innocuous code snippet leads to interesting insight on Matlab’s parser.

Full marks will go to the first person who posts the correct results and reasoning/interpretation of the variants above (hint: it’s not as trivial as it might look at first glance).

Addendum April 9, 2019: I have now posted my solution/analysis of this puzzle here.

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.


Viewing all articles
Browse latest Browse all 111

Trending Articles