【问题标题】:Why does a column vector return a row vector when used to index matrices?为什么列向量用于索引矩阵时会返回行向量?
【发布时间】:2014-09-23 13:23:13
【问题描述】:

假设在 MATLAB 中定义了以下矩阵:

>> matrix=10:18

matrix =

     10    11    12    13    14    15    16    17    18

现在我想用另一个矩阵来索引第一个

>> index=[1,2;3,4]

index =

     1     2
     3     4

>> matrix(index)

ans =

     10     11
     12     13

到目前为止一切顺利,答案的大小与矩阵“索引”的大小相匹配。如果我使用行向量作为索引矩阵,则输出也是行向量。但是当我使用列向量作为索引矩阵时,问题就出现了:

>> index=(1:3)'

index =

     1
     2
     3

>> matrix(index)

ans =

    10    11    12

如您所见,这里答案的大小与矩阵“索引”的大小不一致。索引矩阵和 ans 矩阵大小的这种不一致使我无法编写一段代码来接受任意大小的索引矩阵。

我想知道其他人是否曾经遇到过这个问题并找到了某种解决方案;换句话说,如何强制 MATLAB 给我一个与任意大小的索引矩阵大小相同的 ans 矩阵?

干杯


解决方案

@Dev-iL 很好地解释了here 为什么这是 Matlab 的行为方式,@Dan 提出了一个通用解决方案here。但是,对于我的代码,有一个更简单的临时解决方法,我已经解释过 here

【问题讨论】:

  • 一种解决方法是使用大小。即x = size(index); if x(1) > x(2), matrix(index).';虽然我不知道一个好的解决方案

标签: matlab matrix vector


【解决方案1】:

原因来自函数subsref.m,使用括号时调用:

%SUBSREF Subscripted reference.
%   A(I) is an array formed from the elements of A specified by the
%   subscript vector I.  The resulting array is the same size as I except
%   for the special case where A and I are both vectors.  In this case,
%   A(I) has the same number of elements as I but has the orientation of A.

如您所见,在向量的特殊情况下,结果的形状将与您示例中matrix的形状相同。

至于解决方法,恕我直言Dan has the cleanest solution

【讨论】:

  • 我真希望我能选择两个答案作为接受的答案!您的解释帮助我在我的代码中提出了一种解决方法,这与 @Dan 的不同。谢谢。
  • 请发布您的解决方案,我很乐意更新我的答案。
  • 这没什么特别的,我只是按列定义了我的“矩阵”矩阵。现在,在我的代码中,“矩阵”矩阵是列向量,所有索引矩阵都是二维或列向量;所以总的来说,现在一切似乎都是一致的。等效地,我可以保持“矩阵”矩阵不变,并将所有索引向量更改为行向量。
【解决方案2】:

Dev-iL has explained 为什么会这样。这是一个潜在的解决方法:

reshape(matrix(index),size(index))

【讨论】:

    【解决方案3】:

    预分配大小为index矩阵的输出矩阵。 然后为对应的索引分配对应的值

    out = zeros(size(index));
    out(index) = matrix(index);
    

    示例

    index  = (1:3)'
    
     index =
    
          1
          2
          3
    
     >> out = zeros(size(index))
    
     out =
    
          0
          0
          0
    
     >> in = magic(3)
    
     in =
    
          8     1     6
          3     5     7
          4     9     2
    
     >> out(index) = in(index)
    
     out =
    
          8
          3
          4
    
     >> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-19
      • 1970-01-01
      相关资源
      最近更新 更多