Defining and Indexing Arrays
· One
of the strengths of MATLAB is the capability to handle large collections of
numbers, called arrays, as if they
were a single variable. In fact, MATLAB handles the more familiar scalar variable
as if it were an array that contains only one number or element. Indeed, in the
last chapter, we saw how the range of motion of a piston is readily calculated
with only a few commands for a range of values of crankshaft angle. As you work
through the assigned sections of Chapter 2 you should see some of these
strengths revealed in the simple examples in the text. In general, any
mathematical operation that you can execute on a scalar variable can be
executed on every element in an array with much the same simplicity. In order to operate on arrays, we must first
know how to define arrays and extract specific subsets of data (indexing) in an
array.
· Type
in the lines below (all but the comment lines) one-by-one into the command
window. Try to make sense of each
command and MATLAB’s response as you go.
Don’t rush this, it is critical stuff!!
%%% Clear everything and start fresh
clear all;close all;clc;
%%% Row vector
r1=[2 4 10 15 23]
r2=[5,6,7]
%%% Column vector
s1=[3;0;7]
s2=[2
5
8]
%%% Special array commands
x1=[2:.2:14]
x2=linspace(5,6,20)
x3=logspace(1,3,20)
%%% Setting up two dimensional arrays
M=[2 5;-3 4;-7 1]
N=[4 7 8
8 -2 -4
6 -3 0
-1 0 5]
%%% 1D Array (vector) indexing
r1=[2 4 10 15 23]
r1(1) % first
element
r1(3) % element
3
r1([2:4]) %
elements 2,3,4
r1([1:2:5]) %
every other element 1,3,5
%%% 2D Array indexing
% Singe Elements
N(2,2)
% Column
N(:,2)
% Row
N(3,:)
%%% Special operations
% Size
[m,n]=size(N)
% Transposition
Nt=N'
% Maxima and minima
[x,y]=max(N)
[x,y]=min(N)
max(N)
max(N’)
% Sum (for a 2D matrix, sums columns, for a vector sums all
elements).
sum(N)
sum(N’)
sum(sum(N))
% Turning a multidimensional array into a vector
Nv=N(:)
sum(Nv)