# JMathLabTutorial:4 Variables

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Contents

# Variables

## Standard Variables

Variables are declared by supplying a name and value in the format name=value. The name can be any character sequence. With the exception of the first character it may also contain numbers. The value is any number or expression.

x=24+3i

You can extract real and imaginary parts as:

ans=realpart(24+3i); printf('%f\n',ans)
ans=imagpart(24+3i); printf('%f\n',ans)

## Stored variables

Some variables are predefined (like pi).

x=pi;  printf('%f\n',x)  % PI value
x=eps; printf('%f\n',x)  % eps value

The last previous result of a calculation is stored in the variable ans. All variables are displayed by the command who. Single variables can be deleted by entering clear variable.

x=23+3i
who

Now let us clear the variable from the memory:

x=23+3i
clear(x)
who

Here is an example of calculation of the skin surface of your body from height $h$ and weight W using DuBois' formula:

h=182; W=71; A=h^0.725*W^0.425*71.84e-4
printf('%f',A)

## Example

One calculate some elements of the recursively defined sequence

$x_0=1, x_{n+1} = \frac{1}{2} (x_n + 3/x_n)$

When does this sequence approach its limit $\sqrt{3}$ to within 2*eps?

x=1
x=1/2*(x+3/x);    % n= 1
printf('%f\n',x-sqrt(3))
x=1/2*(x+3/x);   % n= 2
printf('%f\n',x-sqrt(3) )
x=1/2*(x+3/x);   % n= 3
printf('%f\n',x-sqrt(3))
x=1/2*(x+3/x);   % n= 4
printf('%f\n',x-sqrt(3))
x=1/2*(x+3/x);  % n= 5
printf('%f\n',x-sqrt(3))

## Symbolic variables

With few exceptions most operations accept any mixture of numeric and symbolic arguments using the same commands and command syntax.

Symbolic variables should not be confused with variables as discussed until now. These latter variables serve as address for an object in memory (the "environment"), while symbolic variables are algebraic objects on their own. That means if x is a conventional variable, entering x in the text input field makes the program to search in the environment for the corresponding object, which then replaces x. If however x is a symbolic variable, the same action will lead to the creation of a first-degree polynomial with variable x and coefficients 1 and 0.

Each symbolic variable x must be declared as symbolic by entering "syms x" before using it. The command clear x deletes the symbolic (actually any) variable x.

x=3;                % non-symbolic variable
a=x^2+3-2*sin(x);   % placeholder for '3'
printf('%f',a)      % print 3

This creates a function with a symbolic value "x"

syms x             % symbolic variable
y=x^2+3-2*sin(x)   % create function
printf('%f',y)     % ans = -2*sin(x)+(x^2+3)

You can output any symbolic variable as well:

syms x
y=x+2
printf('%f',y)

The answer is "x+2". Here are a few more examples:

syms x,y;
a=2*sqrt(x)*exp(-x^2);
ff=subst(3,x,a);
printf('%f\n',ff);
ss=trigrat(sqrt(4*y^2+4*x*y-4*y+x^2-2*x+1));
printf('%f\n',ss);