3 views (last 30 days)

Show older comments

Hello. My prof gave this code in class but I dont really understand how X(2:1:-1, 3:-1:1) produced ans2 = [6, 5, 4; 3, 2, 1]. His code is as follows:

X=[1,2,3;4,5,6]

ans1= [1, 2, 3; 4, 5, 6]

X(2:-1:1, 3:-1:1)

ans2= [6, 5, 4; 3, 2, 1]

Can someone please explain to me how ans2 is computed? Thank you.

Dave B
on 11 Sep 2021

Here's how I'd break this down. First, let's have a look at what the syntax produced for X:

X=[1,2,3;4,5,6]

So X is a matrix. It has two rows, the first row has the numbers 1,2,3 and the second row has the numbers 4,5,6. All of this is just the meaning of the [ the , and the ; in MATLAB

In the next step we're going to index into X. When you index into a matrix, you provide rows and columns. Before we look at how you indexed into X, let's do some simpler versions:

X(1,1) % row 1 column 1

X(2,1) % row 2 column 1

X(1,3) % row 1 column 3

X(2,3) % row 2 column 3

There's just one more character we need to understand to fully grasp the syntax, which is the colon (:). Let's experiment with colon in a few ways:

1:5 % generate the numbers between 1 and 5, with an increment of 1

1:2:10 % generate the numbers between 1 and 10 with an increment of 2

3:-1:1 % generate the numbers between 3 and 1 with an increment of -1

Now you hopefully can parse X(2:-1:1, 3:-1:1)

It says we're going to be looking at the matrix X, and the rows we want will be row numbers between 2 and 1 with an increment of -1, and the column numbers are between 3 and 1 with an increment of -1. Let's just see those row numbers and column numbers in case it's unclear:

2:-1:1 % rows

3:-1:1 % columns

And that's it, hopefully ans2 now makes sense!

X(2:-1:1, 3:-1:1)

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

Start Hunting!