Assigning Values to Variables in Matlab

MatlabBasics → Variables in Matlab

Like all programming languages, we can declare variables in Matlab and can assign values to them. When a variable is given a value, that value is actually placed in the memory space assigned to the variable. Matlab shows all the declared variables and their values in the right column. For example, assign value 5 to variable x, 7 to variable y, and 12 to variable z and press Enter.

Figure: Assigning Values to Variables in Matlab

Now, suppose we have to find the value of A when A=x+y+z where x=20, y=11 , and z=-3 . We can find it in the following way.

>> x=20;
>> y=11;
>> z=-3;
>> A=x+y+z
A =
28

We can also write the above code in the following way.

>> x=20; y=11; z=-3;
>> A=x+y+z
A =
28

Notice that if a semicolon is typed at the end of the command and Enter key is pressed, the Matlab stored the variable in the memory but does not display it. Besides, it is a good practice to declare all the variables on the same line.

Example Suppose $1,000 is deposited in a savings account that earns compounded interest at a rate of 10% per year. How much will be in the account after 2 years if interest is compounded:
(a) Monthly
(b) Weekly

Solution
(a) When interest is compounded monthly, the Matlab code is

>> P=1000; r=0.1; t=2; n=12;
>> A=P*(1+r/n)^(n*t)
A =
1220.39

(b) When interest is compounded weekly, the Matlab code is

>> P=1000; r=0.1; t=2; n=52;
>> A=P*(1+r/n)^(n*t)
A =
1221.17

NOTE: Matlab is case-sensitive, that means a≠A. Consider the following example,

>> a=10; A=15; b=20; B=25;
>> C=a+b
C =
30

>> D=A+B
D =
40