필터 지우기
필터 지우기

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 CenterFile Exchange에서 Whos에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by