使用向量化方法代替FOR循环创建多维移位数组。

问题描述 投票:0回答:1

我可以 "矢量化 "circashift命令,但我在添加尺寸时遇到了问题。

请看下面的代码 工作循环 矢量化,我试图使用尺寸为

clear all,clf reset,tic,clc , close all

function  [outMat] =  vectcircshift(vectToShift,shiftVector)
%This function generates a matrix where each row is a circshift of the
%original vector from the specified interval in the shiftVector;
%
%Inputs
%vectToShift:   is the original vector you want to circshift multiple times
%shiftVector:   is the vector of the circshift sizes;
%
%Outputs
%outMat:        is a matrix were every row is circshift by the amount in the
%               shiftVector
  [n,m]=size(vectToShift);
  if n>m
    inds=(1:n)';
    i=toeplitz(flipud(inds),circshift(inds,[1 0]));
    outMat=vectToShift(i(shiftVector,:));
    outMat=circshift(outMat,[0,-1]); %shift to include original signal first
  else
    inds=1:m;
    i=toeplitz(fliplr(inds),circshift(inds,[0 1]));
    outMat=vectToShift(i(shiftVector,:));
    outMat=circshift(outMat,[0,-1]); %shift to include original signal first
  end
end

%%----Working FOR LOOP below I'm trying to vectorize.
ndim=0;
ndim_tot=[1:3] %total dimensions
for ndim=1:length(ndim_tot)
  ndim=ndim+0
  if ndim==1
      array_sort(ndim,:)=circshift(ndim_tot,[0 ndim-1]) %start at row of sort array
  else
      array_sort(ndim,:)=circshift(ndim_tot,[0 mod(-ndim,length(ndim_tot))+1]) %next start of row of sort array

  endif
  array_sort= array_sort(ndim,:)
  array_dim(:,:,ndim)=vectcircshift([1:5],array_sort)
endfor

我累了下面的语法,但这个逻辑无法工作。

ndim_tot=[1:3]; %number of dimensions
array_dim2(:,:,ndim_tot)=vectcircshift([1:5],[1:3])

我得到了一个错误的不符合要求的参数(op1是0x0x1,op2是3x5)

我的目标是创建一个多维数组,它可以循环移动信号数组,也可以在多个维度上创建和移动它。

Example: of what the multidimensional array would look like
if I start with a signal / array a1=[1 2 3 4 5]

I'm trying to have it create.

array_dim(:,:,1)=
[
1 2 3 4 5
5 1 2 3 4
4 5 1 2 3
]

array_dim(:,:,2)=
[
5 1 2 3 4
4 5 1 2 3
1 2 3 4 5
]

array_dim(:,:,3)=
[
4 5 1 2 3
1 2 3 4 5
5 1 2 3 4
]

请注意:数字不会是顺序的,我只是用它作为一个例子,以帮助解释事情更容易一点。

PS:我使用的是Octave 4.2.2。

arrays multidimensional-array vectorization octave
1个回答
1
投票

不清楚为什么你在model 3中要移位,但这里有一个使用shift的循环赋值

a1=[1 2 3 4 5];
array_dim=zeros(3,5,3);

for i=0:2
        array_dim(:,:,i+1)=[shift(a1,i);
                shift(a1,mod(i+1,3));
                shift(a1,mod(i+2,3))];
endfor

array_dim

而输出符合你的例子

array_dim =

ans(:,:,1) =

   1   2   3   4   5
   5   1   2   3   4
   4   5   1   2   3

ans(:,:,2) =

   5   1   2   3   4
   4   5   1   2   3
   1   2   3   4   5

ans(:,:,3) =

   4   5   1   2   3
   1   2   3   4   5
   5   1   2   3   4
© www.soinside.com 2019 - 2024. All rights reserved.