【问题标题】:Vectorizing and De-vectorizing parts of matrices矩阵的向量化和去向量化部分
【发布时间】:2017-06-30 15:22:14
【问题描述】:

我很难理解这段代码中的错误在哪里:

我有一堆矩阵,我想取出每个矩阵的上三角部分,将其放入向量中,对其进行处理,然后将结果映射回来。代码如下:

%%
n=10;
m=3;

% generate a random 'stack of matrices'
bar=randn(n,n,m);

% index the upper triangular part
inds=triu(true(n,n));

% linearize
bar_lin=permute(bar,[3 1 2]);
bar_lin=bar_lin(:,inds);

% de-linearize
foo=zeros(size(bar,3),n,n);
foo(:,inds)=bar_lin;
foo=permute(foo,[2 3 1]);

% why is this not == 0 ??
sum(foo(:)-bar(:))

我只是不明白为什么这不起作用!谢谢!

【问题讨论】:

  • 添加了 matlab 标签 - 希望这有助于找到正确的受众

标签: matlab indexing vectorization


【解决方案1】:

您的最后一行代码不会返回0。这是因为bar 变量存储矩阵的上三角部分和下三角部分,而 foo 只存储上三角部分。你基本上是在减去这样的东西

bar = [1 2 3;
       4 5 6;
       7 8 9]
foo = [1 2 3;
       0 5 6;
       0 0 9]
foo - bar = [ 0  0  0;
             -4  0  0;
             -7 -8  0]
% Thus it will not be 0 for this case
% even sum(foo(:) - bar(:)) will not be 0

只有当较低的部分(不在 foo 中的部分)总和为 0 时,您才会得到输出为 0(但在随机数的情况下这种情况很少见)

【讨论】:

  • jup,谢谢。我刚刚看到了。尴尬……基本上,忘记加bar(repmat(not(inds),[1 1 m]))=0;了。
猜你喜欢
  • 2014-02-22
  • 1970-01-01
  • 1970-01-01
  • 2019-04-25
  • 2014-01-03
  • 2011-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多