【问题标题】:Vectorise a code to transform a vector into a matrix向量化代码以将向量转换为矩阵
【发布时间】:2017-12-07 17:20:51
【问题描述】:

我在 MATLAB 中有一个维度为 Nx1 的向量 A,例如

N = 5;
A = [1
     2
     3
     4
     5];

我想构造一个维度为(N-1) x N 的矩阵B,这样:
对于i=1,...,NB(:,i) 包含1,2,...,i-1,i+1,...,N 的行A


在上面的例子中,

B = [2 1 1 1 1
     3 3 2 2 2
     4 4 4 3 3
     5 5 5 5 4]

这段代码做我想做的事:

 B=zeros(N-1,N);
 for i=1:N
     if i>1 && i<N
         B(:,i)=[A(1:i-1); A(i+1:end)];
     elseif i==1
         B(:,i)=A(i+1:end);
     elseif i==N
         B(:,i)=A(1:i-1);
     end
 end

但我想将它矢量化。有什么帮助吗?

【问题讨论】:

    标签: matlab matrix vector vectorization


    【解决方案1】:

    这是nchoosek 顺时针生成的90 degree rotation

    B = rot90(nchoosek(A,N-1),-1);   
    

    【讨论】:

      【解决方案2】:

      这是一个简单的选项:

      [r, ~] = find(~eye(N));
      B = reshape(A(r), N-1, N)
      

      【讨论】:

        【解决方案3】:

        根据您的示例,您可以删除每个 N+1 条目:

        N=5;
        a=repmat(1:N,1,N); % make an NxN long vector 
        a(1:N+1:end)=[]; % delete every N+1 entry
        B=reshape(a,N-1,[]) % reshape to N-1 x N matrix
        

        【讨论】:

          猜你喜欢
          • 2017-06-10
          • 1970-01-01
          • 2021-04-29
          • 2010-12-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多