We already have experience working with arrays from studying the C programming language. There are some subtle and some not-so-subtle differences with working with arrays in MATLAB, some of them syntactical and others more fundamental. The main differences from C are:
In MATLAB you can select or address more than one array element at once and thus perform operations with multiple elements at once. This will become clearer as soon as we look at some examples.
Arrays in MATLAB are ones-based (1-N) rather than zero-based. For example, if A = [5 -2 4 3] is your array, then the โ5โ is located at index โ1โ of the array in MATLAB whereas in C we would use the index โ0โ. So in MATLAB, A[1] = 5 whereas in C, A(0) = 5.
Here are some examples of how to find the kth element of a vector โveโ or the element in row k and column p of matrix โmaโ in MATLAB. Do you remember how to address the equivalent elements in C?
You can also select entire ranges of elements in an array. The colon operator : is often used for this purpose. Its use is most easily understood by looking at some examples.
>> % matrix examples:
>> ma(:,j) % all rows, column j (result is nrow by 1)
>> ma(i,:) % row i, all columns (result is 1 by ncol)
>> ma(:,p:q) % columns p through q
>> ma(p:q,:) % rows p through q
>> ma(p:q,r:s) % rows p to q of cols r to s
Note that when you address multiple elements, the result is a vector or matrix of the selected size:
You can explicitly list the indices, in your desired order, whose corresponding elements you are interested in. Note that these indices are listed inside the parentheses of โu(...)โ in the form of a vector, so enclosed in brackets.