# 1D Arrays in MATLAB

*Article posted on Sunday, 1st, July, 2012 at 1:37 pm*

***BREAKING NEWS*** MATLAB counts from the number 1! What a crazy notion this is! Originally, I got so used to programming counts from 0, that this confused the life out of me – it’s quite intuitive once you re-adjust though…

What does that mean for arrays though? Well, It’s quite important if you want to access parts of them. You’ll see why soon.

To set up a new array in MATLAB, it’s quite simple. You can set up multi-dimensional arrays, which can get confusing so we’ll start by making a 1D array, or more commonly known to most people, a **list**.

% Make a new 1D array my_1D_array = [1 2 3 4 5 6 7 8 9 10 11 12];

See how easy that was? All you do is use the square brackets, and put in your numbers! The numbers are separated by a space, nothing more, nothing less. Try viewing it by just typing the variable name into the terminal:

my_1D_array = 1 2 3 4 5 6 7 8 9 10 11 12

Now to get the first number in that list, you simply have to provide the array variable name, and then next to that in normal brackets ( ) put the number 1. If you want to get the third value, put 3 and so on. To go back to the start, if you have come from another programming language, you’ll be used to counting from 0 rather than 1 – using 0 for the first item, 2 for the third, etc.

my_1D_array(3) ans = 3

Note that you can only do this with **numbers**. If you try to do this with strings, it will just concatenate (join) them together. If you want to make a list of strings, you need to use a **cell array**.

Cell arrays are pretty much the same as regular arrays, but you use curly braces { } instead of square brackets. You can use numbers or strings for these, so I’ll demonstrate the use of strings:

my_1D_cell_arr = {'hello' 'hi' 'yo' 'hola' 'bonjour' 'guten tag' };

See how it’s exactly the same but with different brackets? Also, the strings still need the single quotes, otherwise MATLAB will think you’re using variable names.

To access the third value, its the same as numeric arrays, but just with the curly braces:

my_1D_cell_arr{3} ans = yo

Easy huh? Well these arrays are great for using with for loops! Stay tuned for a post on that soon…

Tags: array, column, MATLAB, row, variable