initialize array in matlab

In Matlab, arrays can be initialized using either the colon operator, linspace function or by manually assigning values to each element. Here are some examples:

Using colon operator:

main.m
arr1 = 1:5; % creates a row vector with elements 1 2 3 4 5
arr2 = 1:0.5:5; % creates a row vector with elements 1 1.5 2 2.5 3 3.5 4 4.5 5
138 chars
3 lines

Using linspace function:

main.m
arr3 = linspace(0,10,11); % creates a row vector with 11 equally spaced elements between 0 and 10
98 chars
2 lines

Manually assigning values:

main.m
arr4 = [2, 4, 6, 8, 10]; % creates a row vector with elements 2 4 6 8 10
arr5 = [1 2 3; 4 5 6; 7 8 9]; % creates a 3x3 matrix with elements 1 2 3; 4 5 6; 7 8 9
160 chars
3 lines

To access individual elements in an array, use indexing. For example:

main.m
arr = [1 2 3 4 5];
arr(3) % retrieves the third element of arr, which is 3
75 chars
3 lines

gistlibby LogSnag