University of Alaska Fairbanks
Geophysical Institute

Beyond the Mouse 2010 - The geoscientist's computational chest.

Lab 2: Matlab, Variables

"Programming is legitimate and necessary academic endeavor."
Donald E. Knuth

Lab slides

matlab prep (pdf)

Introduction

Today we want you to play with variables, relational and logical operators in Matlab. This is a basis to understand flow control later on. We give you a list of examples to play with and want you to explain the results Matlab gives you. I don't care which way you'll play around, but I expect the result to be a Matlab script file (ends in .m) similar to my template. Your resulting script file will contain one line or a block of lines I give below and then one or many disp statements that explain the code and the response Matlab gives. After the last disp call you will place a pause statement. This serves two functions: 1) It's easy for me to look through, 2) you have documentation in form of a script (you may wanna call it relop_doc.m)

Exercise 0: ans

Open Matlab, type help ans or doc ans and understand what the variable ans is.

Exercise I: Assignments and Comparisons

Open Matlab and type the following lines in the command window. Explain each of Matlab's responses to your input!

test_var == 1
test_var = 1
test_var == 1
test_var == 5

Now, let's try something fancy:

test_var == 'A'
test_var = 65
test_var == 'A'
test_var == 'MATLAB'

What's with that? Hint.

Now create a vector that will answer the question:

>> test_var == 'MATLAB'

with:

ans =

1 1 1 1 1 1

Exercise II: Relational Operators

Open Matlab and type doc relop or help relopin the command window and read up on relational operators in Matlab.

Now we have more input. i and j are special, predefined variables in Matlab; the imaginary unit sqrt(-1). Do you think this statement is true?

0 > i^2 && sqrt(-1) > j

Now explain this - what's going on with the alternating results for the xor statement?

0 > i^2
xor(ans,1)
xor(ans,1)
xor(ans,1)

In Matlab the elementwise logical operators &, |, and xor compare elements of arrays and vectors to each other. Reproduce the following results using two arrays and one logical operator:

ans = 0 1 1 1
ans = 0 0 0 1
ans = 0 1 1 0

What are the answers to the deeper questions of life ... an why?

'2b' | ~'2b'
'MATLAB' == 'GMT'
'MATLAB' == 'GMT   '

ronni <at> gi <dot> alaska <dot> edu | last changed: September 23, 2010