Borrar filtros
Borrar filtros

hi everyone , how can I built a matrix of circularly shifted array in efficient way

5 visualizaciones (últimos 30 días)
I have a given initial array of length M , I want to built a matrix of MxM , by circularly shifting this array, example
for array=[2,0,0] the matrix should be matrix=[2,0,0;0,2,0;0,0,2]
my code works but it not efficient for large M I would be happy if someone can gives me an efficient suggestion
my code:
array=[2,0,0]; % given Initial array
M=length(array);
mat=zeros(M,M);%matrix
mat(1,:)=array;
for i=2:M
array=circshift(array(1,1:M),[0 1]);
mat(i,:)=array;
end

Respuesta aceptada

Stephen23
Stephen23 el 19 de Feb. de 2018
Editada: Stephen23 el 19 de Feb. de 2018
Multiple circshift calls in a loop is not required. One call to toeplitz is simpler:
>> V = [2,0,0];
>> toeplitz(V([1,end:-1:2]),V)
ans =
2 0 0
0 2 0
0 0 2
Or a clearer example:
>> V = [4,3,2,1,0];
>> toeplitz(V([1,end:-1:2]),V)
ans =
4 3 2 1 0
0 4 3 2 1
1 0 4 3 2
2 1 0 4 3
3 2 1 0 4

Más respuestas (1)

Guillaume
Guillaume el 19 de Feb. de 2018
Editada: Guillaume el 19 de Feb. de 2018
To be compared to a loop version, it's very possible that a loop is faster:
array = [2, 0, 0];
shiftidx = hankel(1:numel(array), circshift(1:numel(array), 1))
M = array(shiftidx)
Or, for a shift in the other direction:
array = [2, 0, 0];
shiftidx = toeplitz(1:numel(array), [1, numel(array):-1:2])
M = array(shiftidx.')

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by