matlab 矩阵元素表示方法转换 A(a) to A(x,y)

linearInd = sub2ind(matrixSizerowSubcolSub) returns the linear index equivalents to the row and column subscripts rowSub andcolSub for a matrix of size matrixSize. The matrixSize input is a 2-element vector that specifies the number of rows and columns in the matrix as [nRowsnCols]. The rowSub and colSub inputs are positive, whole number scalars or vectors that specify one or more row-column subscript pairs for the matrix. Example 3 demonstrates the use of vectors for the rowSub and colSub inputs.

Examples

Example 1

This example converts the subscripts (2, 1, 2) for three-dimensional array A to a single linear index. Start by creating a 3-by-4-by-2 array A:

rand('state', 0);   % Initialize random number generator.
A = rand(3, 4, 2)

A(:,:,1) =
    0.9501    0.4860    0.4565    0.4447
    0.2311    0.8913    0.0185    0.6154
    0.6068    0.7621    0.8214    0.7919
A(:,:,2) =
    0.9218    0.4057    0.4103    0.3529
    0.7382    0.9355    0.8936    0.8132
    0.1763    0.9169    0.0579    0.0099

Find the linear index corresponding to (2, 1, 2):

linearInd = sub2ind(size(A), 2, 1, 2)
linearInd =
    14

Make sure that these agree:

A(2, 1, 2)            A(14)
ans =                 and =
     0.7382               0.7382

Example 2

Using the 3-dimensional array A defined in the previous example, specify only 2 of the 3 subscript arguments in the call to sub2ind. The third subscript argument defaults to 1.

The command

linearInd = sub2ind(size(A), 2, 4)
ans =
    11

is the same as

linearInd = sub2ind(size(A), 2, 4, 1)
ans =
    11

Example 3

Using the same 3-dimensional input array A as in Example 1, accomplish the work of five separate sub2ind commands with just one.

Replace the following commands:

sub2ind(size(A), 3, 3, 2);
sub2ind(size(A), 2, 4, 1);
sub2ind(size(A), 3, 1, 2);
sub2ind(size(A), 1, 3, 2);
sub2ind(size(A), 2, 4, 1);

with a single command:

sub2ind(size(A), [3 2 3 1 2], [3 4 1 3 4], [2 1 2 2 1])
ans =
    21    11    15    19    11

Verify that these linear indices access the same array elements as their subscripted counterparts:

[A(3,3,2),   A(2,4,1),   A(3,1,2),   A(1,3,2),   A(2,4,1)]
ans =
    0.0579    0.6154    0.1763    0.4103    0.6154

A([21, 11, 15, 19, 11])
ans =
    0.0579    0.6154    0.1763    0.4103    0.6154
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值