Borrar filtros
Borrar filtros

how set diagonal =1 in matrix tridimensional a(:,:,:)

1 visualización (últimos 30 días)
aldo
aldo el 19 de Jul. de 2023
Editada: Bruno Luong el 20 de Jul. de 2023
hi,
how can i set=1 the diagonal of the multidimensional matrix
size(COR)
ans =
8 8 188
  8 comentarios
Bruno Luong
Bruno Luong el 20 de Jul. de 2023
Editada: Bruno Luong el 20 de Jul. de 2023
Here is the timings of three methods
COR = rand(8,8,188);
timeit(@() methodfor(COR)) % Aldo
ans = 4.0301e-05
timeit(@() methodlogical(COR)) % Walter
ans = 2.3801e-05
timeit(@() methodindex(COR)) % Bruno
ans = 1.6800e-05
function COR = methodfor(COR)
[r,c,d]=size(COR);
for i=1:d
for x=1:r
COR(x,x,i)=1;
end
end
end
function COR = methodlogical(COR)
M = repmat(logical(eye(size(COR,1),size(COR,2))),1,1,size(COR,3));
COR(M) = 1;
end
function COR = methodindex(COR)
[b,c,d] = size(COR);
COR(1+(b+1)*(0:min(b,c)-1)'+b*c*(0:d-1)) = 1;
end
aldo
aldo el 20 de Jul. de 2023
okk thank

Iniciar sesión para comentar.

Respuestas (3)

Geovane Gomes
Geovane Gomes el 19 de Jul. de 2023
Maybe using eye and repmat
COR = repmat(eye(8),1,1,188);
size(COR)
ans = 1×3
8 8 188
  3 comentarios
Walter Roberson
Walter Roberson el 20 de Jul. de 2023
M = repmat(logical(eye(size(COR,1),sie(COR,2))),1,1,size(COR,3));
COR(M) = 1;
aldo
aldo el 20 de Jul. de 2023
Correct! thank you

Iniciar sesión para comentar.


Bruno Luong
Bruno Luong el 20 de Jul. de 2023
% Generate dummy test data
a = 0.01*rand(2,3,4)
a =
a(:,:,1) = 0.0058 0.0073 0.0096 0.0027 0.0011 0.0010 a(:,:,2) = 0.0081 0.0020 0.0006 0.0038 0.0068 0.0023 a(:,:,3) = 0.0052 0.0037 0.0065 0.0073 0.0024 0.0026 a(:,:,4) = 0.0057 0.0047 0.0098 0.0098 0.0082 0.0040
[b,c,d] = size(a);
[I,K] = ndgrid(1:min(b,c),1:d);
a(sub2ind([b,c,d],I,I,K)) = 1;
a
a =
a(:,:,1) = 1.0000 0.0073 0.0096 0.0027 1.0000 0.0010 a(:,:,2) = 1.0000 0.0020 0.0006 0.0038 1.0000 0.0023 a(:,:,3) = 1.0000 0.0037 0.0065 0.0073 1.0000 0.0026 a(:,:,4) = 1.0000 0.0047 0.0098 0.0098 1.0000 0.0040

Bruno Luong
Bruno Luong el 20 de Jul. de 2023
% Generate dummy test data
a = 0.01*rand(2,3,4)
a =
a(:,:,1) = 0.0023 0.0073 0.0085 0.0021 0.0024 0.0021 a(:,:,2) = 0.0073 0.0066 0.0072 0.0021 0.0099 0.0025 a(:,:,3) = 0.0035 0.0094 0.0085 0.0008 0.0069 0.0050 a(:,:,4) = 0.0070 0.0079 0.0051 0.0071 0.0029 0.0022
[b,c,d] = size(a);
a(1+(b+1)*(0:min(b,c)-1)'+b*c*(0:d-1)) = 1;
a
a =
a(:,:,1) = 1.0000 0.0073 0.0085 0.0021 1.0000 0.0021 a(:,:,2) = 1.0000 0.0066 0.0072 0.0021 1.0000 0.0025 a(:,:,3) = 1.0000 0.0094 0.0085 0.0008 1.0000 0.0050 a(:,:,4) = 1.0000 0.0079 0.0051 0.0071 1.0000 0.0022

Categorías

Más información sobre Operating on Diagonal Matrices 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