How to compute a vector

1 回表示 (過去 30 日間)
Lavorizia Vaughn
Lavorizia Vaughn 2021 年 9 月 11 日
回答済み: Dave B 2021 年 9 月 11 日
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 件のコメント
Atsushi Ueno
Atsushi Ueno 2021 年 9 月 11 日
It must be X(2:-1:1, 3:-1:1), not X(2:1:-1, 3:-1:1).
Lavorizia Vaughn
Lavorizia Vaughn 2021 年 9 月 11 日
sorry. I have made the necessary corrections.

サインインしてコメントする。

回答 (1 件)

Dave B
Dave B 2021 年 9 月 11 日
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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by