Matlab中不同位置数的矩阵的每一行的左圆移位 [英] Left circular shift in Matlab for each row of a matrix of a different number of positions
问题描述
我在Matlab中有一个矩阵 A
,维度为 mxn
,由零和一组成,矩阵为 J
,维度为 mx1
报告 {1,...,n}
中的一些整数.
I have a matrix A
in Matlab of dimension mxn
composed of zeros and ones, and a matrix J
of dimension mx1
reporting some integers from {1,...,n}
.
我想构造一个维度 mxn
的矩阵 B
使得对于
I want to construct a matrix B
of dimension mxn
such that for
(1) B(1,:)= A(1,:)
(2)多个位置等于(J(1)-1)+(J(2)-1)+ ... +(J(i-1)-1)的LEFT圆代码>
这段代码可以满足我的要求
This code does what I want
m=4;
n=5;
A=[1 0 1 1 0; ...
0 1 0 0 1; ...
1 1 0 0 0; ...
0 0 0 0 1;
J=[2;1;5;8];
B=zeros(m,n);
B(1,:)=A(1,:);
foridx=cumsum(J); %mx1
shift=foridx-(1:1:m).'; %mx1
v=shift(1:m-1); %(m-1)x1
for i=2:m
B(i,:)=(circshift((A(i,:)).', -v(i-1),1)).';
end
我想避免最后的循环.我喜欢在此处由Divakar提供,但它用于右圆移.
I would like to avoid the final loop. I like the answer here by Divakar but it is for a right circular shift.
Arelevant=A(2:end,:);
idx0 = mod(bsxfun(@plus,n-v(:),1:n)-1,n);
out = Arelevant(bsxfun(@plus,(idx0*(m-1)),(1:(m-1))'));
B(2:end,:)=out;
您能帮我做一些类似的左移吗?
Could you help me to have something similar for a left circular shift?
推荐答案
这里有一个小技巧,可以在不循环的情况下执行此操作.
Here is a little trick to perform this operation without loop.
我使用fft来移动每一行.
I use an fft in order to shift each line.
m=4;
n=5;
A=[1 0 1 1 0; ...
0 1 0 0 1; ...
1 1 0 0 0; ...
0 0 0 0 1;]
J=[2;1;5;8];
foridx=cumsum(J); %mx1
shift=foridx-(1:1:m).'; %mx1
v=[0;shift(1:m-1)]; %(m-1)x1
L=real(round(ifft(fft(A,[],2) .* exp(2i*pi/n*v*(0:m)) ,[],2))) %left shift
R=real(round(ifft(fft(A,[],2) .* exp(-2i*pi/n*v*(0:m)) ,[],2))) %right shift
这篇关于Matlab中不同位置数的矩阵的每一行的左圆移位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!