Matlab 矩阵的矢量化和去矢量化部分
我很难理解此代码中的错误是: 我有一堆矩阵,我想取每个矩阵的上三角部分,把它放到一个向量中,用它做点什么,然后把结果映射回来。代码如下:Matlab 矩阵的矢量化和去矢量化部分,matlab,indexing,vectorization,Matlab,Indexing,Vectorization,我很难理解此代码中的错误是: 我有一堆矩阵,我想取每个矩阵的上三角部分,把它放到一个向量中,用它做点什么,然后把结果映射回来。代码如下: %% 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=
%%
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(:))
我就是不明白为什么这样不行!谢谢 您的最后一行代码将不会返回
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的输出(但在随机数的情况下这将是罕见的)添加了matlab标记-希望这有助于找到正确的AudienceUp,谢谢。我刚才看到了。令人尴尬的基本上,忘记添加
条(repmat(不是(inds),[1 m]))=0代码>。