MATLAB: Using a loop to solve the following matrix. Using a loop to solve the following matrix. I have almost resolved, they could help me

matlab function

Good afternoon, I need to know how to create a matrix with Matlab (in any order), in which the diagonal is formed by 0 and the remaining numbers are 1 and -1 alternately. He conseguido casi resolverla de esta manera:
dim=6; % dimension de la matriz
Z=rand(dim);
Z(Z>.6)=1;Z(Z<.6)=-1;
for j=1:dim
Z(j,j)=0;
end;
Pero necesito que sea de forma alternada 1,-1,1,-1,1… y la diagonal 0 I would greatly appreciate an answer!

Best Answer

Random -1 and +1 (like your example):
>> N = 6;
>> X = [-1,1];
>> X(randi(2,N)).*~eye(N)
ans =
0 1 1 -1 1 1
-1 0 1 1 1 1
1 1 0 -1 -1 -1
-1 1 -1 0 -1 -1
-1 1 -1 1 0 -1
-1 -1 -1 1 -1 0
or in one line:
>> (2*randi(2,N)-3).*~eye(N)
Alternating (like your explanation):
>> toeplitz(2*mod(0:N-1,2)-1).*~eye(N)
ans =
0 1 -1 1 -1 1
1 0 1 -1 1 -1
-1 1 0 1 -1 1
1 -1 1 0 1 -1
-1 1 -1 1 0 1
1 -1 1 -1 1 0
Related Question