Matlab 矩陣索引

來源:互聯網
上載者:User

擷取矩陣元素

A(row, column)

線性索引

matlab儲存矩陣並非以它的形狀的形式,而是一個線性元素列,將每一列串連起來。

比如

A = [2 6 9; 4 2 8; 3 5 1]

A =

2 6 9

4 2 8

3 5 1

存為2, 4, 3, 6, 2, 5, 9, 8, 1

所以A(3,2)也為A(6)。

尺寸為[d1 d2]的矩陣A,A(i,j)的線性序號為 (j-1) * d1 + i

與索引形式有關的函數

將行列索引和線性索引轉化的函數。sub2ind/ind2sub

A = [2 6 9; 4 2 8; 3 5 1];

linearindex = sub2ind(size(A), 3, 2)

linearindex =

6

[row col] = ind2sub(size(A), 6)

row =

3

col =

2

擷取多個元素

冒號操作

A = magic(4);

需要:A(1,4) + A(2,4) + A(3,4) + A(4,4)

則:sum(A(1:4, 4))

A(1:4, 4) 提取1到4行,第4列的元素。

非連續元素

從矩陣中擷取非連續元素的值。

使用冒號並指定步長。m:3:n,表示從第m個到第n個元素,每3個取一個。

B = A;

B(1:3:16) = -10

B =

-10 2 3 -10

5 11 -10 8

9 -10 6 12

-10 14 15 -10

使用自定索引序列

A = 5:5:50

A =

5 10 15 20 25 30 35 40 45 50

B = [1 3 6 7 10];

A(B)

ans =

5 15 30 35 50

end關鍵字

在矩陣大小不確定時很有用。

B(1:3:end) = -10

選擇某行或者某列所有元素

第二列:A(:, 2)

第二行:A(2,:)

所有:A(:) 以列向量的形式。

使用矩陣的邏輯索引

在選出A矩陣中與B矩陣內非零值位置相同的元素,為一列向量。所以不是根據值來的,而是根據位置來的。

B是一個矩陣由邏輯0和1組成。即B中為非零的位置,就是要選出的元素位置。

A = [1 2 3; 4 5 6; 7 8 9]

A =

1 2 3

4 5 6

7 8 9

B = logical([0 1 0; 1 0 1; 0 0 1]);

B =

0 1 0

1 0 1

0 0 1

A(B)

ans =

4

2

6

9

find函數返回B中非零元素的索引,

find(B)

ans =

2

4

8

9

所以也就是選出A中序號為2 4 8 9的元素,組成列向量。

例1

rand('twister', 5489);

B = A > 0.5;

A(B) = 0

A =

0 0.0975 0.1576 0.1419 0

0 0.2785 0 0.4218 0.0357

0.1270 0 0 0 0

0 0 0.4854 0 0

0 0 0 0 0

例2

A = magic(4)

A =

16 2 3 13

5 11 10 8

9 7 6 12

4 14 15 1

B = isprime(A) %素數

B =

0 1 1 1

1 1 0 0

0 1 0 0

0 0 0 0

A(~B) = 0; % 邏輯索引

A

A =

0 2 3 13

5 11 0 0

0 7 0 0

0 0 0 0

find(B)

ans =

2

5

6

7

9

13

*使用較小的矩陣作為索引矩陣

大多數情況下,邏輯索引矩陣與對象矩陣大小相同,但索引矩陣也可以小於對象矩陣(不能大於)。

A = [1 2 3;4 5 6;7 8 9]

A =

1 2 3

4 5 6

7 8 9

B = logical([0 1 0; 1 0 1])

B =

0 1 0

1 0 1

isequal(numel(A), numel(B))

ans =

0

A(B)

ans =

4

7

8

MATLAB將索引矩陣中缺少的部分視為0。

以上相當於:

C = logical([B(:);0;0;0]);

isequal(numel(A), numel(C))

ans =

1

A(C)

ans =

4

7

8

單冒號索引

n = [1 2 3; 4 5 6];

c = {1 2; 3 4};

s = cell2struct(c, {'a', 'b'}, 1); s(:,2)=s(:,1);

%cell2struct,將c編入結構中,成員變數為a,b,變數值為c,1為個體排列維數。

對每個使用單冒號索引:

n(:) c{:} s(:).a

ans = ans = ans =

1 1 1

4 ans = ans =

2 3 2

5 ans = ans =

3 2 1

6 ans = ans =

4 2

按索引指定值

當將一個矩陣的值指定給另一個矩陣是,你可以使用任意一種索引方法。

A(J,K,...) = B(M,N,...) JKMN必須是標量,向量或者矩陣。

A中指定元素個數應該與B中指定元素個數相等。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.