array indexing in matlab

Array indexing in MATLAB allows you to access specific elements or subsets of an array. There are a few different ways to perform array indexing in MATLAB, including using the colon operator and logical indexing.

Colon operator

The colon operator (:) is used to create a range of indices. For example, if you want to access all elements of an array from 2 to 5, you can use the following code:

main.m
A = [1, 2, 3, 4, 5];
B = A(2:5);
33 chars
3 lines

This will create a new array B with elements 2 through 5 of A.

The colon operator can also be used to specify a step size. For example, to access every other element of an array, you can use the code:

main.m
A = [1, 2, 3, 4, 5];
B = A(1:2:end);
37 chars
3 lines

This will create a new array B with elements 1, 3, and 5 of A.

Logical indexing

Logical indexing is another way to access specific elements of an array based on a logical condition. For example, to access all elements of an array that are greater than 3, you can use the following code:

main.m
A = [1, 2, 3, 4, 5];
B = A(A>3);
33 chars
3 lines

This will create a new array B with elements 4 and 5 of A.

You can also use logical indexing to modify the elements of an array. For example, to set all elements of an array that are greater than 3 to 0, you can use the following code:

main.m
A = [1, 2, 3, 4, 5];
A(A>3) = 0;
33 chars
3 lines

This will set the elements 4 and 5 of A to 0.

gistlibby LogSnag