Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

B.

Working with Arrays


1. Arrays hold the key in many powerful features of Matlab. Try the following:

>> x = 0 : 10 <Enter>

>> a = [ 1 2 3, 4, 5, 6] <Enter>

>> size(x) <Enter>

2. Arrays can now be defined (or created) in terms of the vector x just defined. Try

>> y = 2.* x <Enter>

>> w = y ./ x <Enter>

>> z = sin(x) <Enter>


>> b = magic(10) <Enter>

3. You can use one vector in a list for another one. Try:

>> a = [ 1 2 3]; <Enter>


>> b = [ 4 5]; <Enter>
>> c = [a –b] <Enter>
>> a = [a 0 -1] <Enter>

4. There are several ways to initialize a vector y.

>> x = 1:10 <Enter>


>> x = 1:0.5:4 <Enter>

>> x = 10:-1:1 <Enter>

>> x = 1:2:6 <Enter>

>> x = 0: -2: -5 <Enter>

>> x=linspace(0, pi/2, 10) <Enter>


5. To transpose a vector, we use an apostrophe (‘). Try:

>> x = 1:5 <Enter>

>> x’ <Enter>

>> y = [ 1 4 8 0 -1]’ <Enter>

6. To refer to particular elements of a vector by means of subscripts, try:

>> r = rand(1,7) <Enter>


>> r(3) <Enter>

>> r(2:4) <Enter>

>> r(1:2:7) <Enter>

>> r([1 7 2 6]) <Enter>

>> r([1 7 2]) = [ ] <Enter>

>> r = [ 1 2 3; 4 5 6; 7 8 9] <Enter>
>> r(3,2) <Enter>

7. To draw a reasonably nice graph of sin(x), enter the following commands:

>> x = 0 : 0.1 : 10; <Enter>


>> z = sin(x); <Enter>
>> plot(x,z), grid <Enter>

>> w = sin(2*x); <Enter>


>> plot(x,w), grid <Enter>

>> ezplot(‘tan(x)’) <Enter>

You might also like