Do Not Understand Two Code Lines

1 view (last 30 days)
kubota555
kubota555 on 29 Nov 2015
Answered: kubota555 on 29 Nov 2015
As a raw beginner with Matlab (but broad experience with Fortran), I am seeking your assistance to help me understand two examples of code as follows. These are drawn from an existing script, and I'm trying to understand what is being done at the basic code level.
Example 1: Say I set up a single dimension array of 9 elements as follows:
array1=[1, 2, 3, 4, 5, 6, 7, 8, 9];
This line then follows:
array1=[array1(9:-1:2),array1];
As a guess only, is the second line converting the initial array into a two dimension array of 8 rows and 9 columns? I do not understand the resulting data arrangement.
Example 2: Again, say I set up a single dimension array of 9 elements as follows:
array2=[1, 2, 3, 4, 5, 6, 7, 8, 9];
This line then follows:
array2=[fliplr(array2(2:9)),array2];
Again, I don't understand the sizing of the second matrix nor the resulting data arrangement in it. I understand the fliplr instruction.
Any clarifying assistance will be greatly appreciated, as I'm at a loss to understand these examples.

Answers (2)

Jan
Jan on 29 Nov 2015
Edited: Jan on 29 Nov 2015
There is no reason for guessing. I suggest simply run the commands and examine the results in the command window:
array1 = [array1(9:-1:2),array1];
The [ and ] mean a concatenation. If the elements are separated by commas, they are concateneated horizontally, with semicolons vertically. The parenthesis ( and ) are used for indexing. 9:-1:1 is the colon operator. It creates the vector from 9 to 1 with the step width -1, so this is:
[9,8,7,6,5,4,3,2,1]
Finally you get the initial array in reversed order and appended the original array.
The second case is similar:
array2=[1, 2, 3, 4, 5, 6, 7, 8, 9];
array2=[fliplr(array2(2:9)),array2];
array2(2:9) is the 2nd to 9.th element of the array. |fliplr reverses the order. And the result is:
[9,8,7,6,5,4,3,2, 1,2,3,4,5,6,7,8,9]
You find exhaustive explanations in the Getting Started chapters of the documentation. It is required to read the instructions, when you want to use such a powerful tool as Matlab.

kubota555
kubota555 on 29 Nov 2015
Thank you for your helpful response to my questions. It's now all clear and understood.
I had checked the documentation on arrays but concatenation never came to my mind, so I never went looking for it. Yes, still more reading to go.
Thanks again.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!