MATLAB Answers

How to compute a vector

2 views (last 30 days)
Lavorizia Vaughn
Lavorizia Vaughn on 11 Sep 2021
Answered: Dave B on 11 Sep 2021
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.
  2 Comments
Lavorizia Vaughn
Lavorizia Vaughn on 11 Sep 2021
sorry. I have made the necessary corrections.

Sign in to comment.

Answers (1)

Dave B
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]
X = 2×3
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
ans = 1
X(2,1) % row 2 column 1
ans = 4
X(1,3) % row 1 column 3
ans = 3
X(2,3) % row 2 column 3
ans = 6
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
ans = 1×5
1 2 3 4 5
1:2:10 % generate the numbers between 1 and 10 with an increment of 2
ans = 1×5
1 3 5 7 9
3:-1:1 % generate the numbers between 3 and 1 with an increment of -1
ans = 1×3
3 2 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
ans = 1×2
2 1
3:-1:1 % columns
ans = 1×3
3 2 1
And that's it, hopefully ans2 now makes sense!
X(2:-1:1, 3:-1:1)
ans = 2×3
6 5 4 3 2 1

Tags

Products

Community Treasure Hunt

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

Start Hunting!

Translated by