how set diagonal =1 in matrix tridimensional a(:,:,:)
Mostrar comentarios más antiguos
hi,
how can i set=1 the diagonal of the multidimensional matrix
size(COR)
ans =
8 8 188
8 comentarios
Walter Roberson
el 20 de Jul. de 2023
Are you looking for the diagonal on each "page", so all 118 layers the same?
Or are you looking for the "space diagonal" -- (1,1,1), (2,2,2), up to (8,8,8) with everything else 0?
aldo
el 20 de Jul. de 2023
aldo
el 20 de Jul. de 2023
Bruno Luong
el 20 de Jul. de 2023
Editada: Bruno Luong
el 20 de Jul. de 2023
So you have for-loop that seems correct and arguably preferable to all answers you'll get. Why asking the question?
aldo
el 20 de Jul. de 2023
aldo
el 20 de Jul. de 2023
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
timeit(@() methodlogical(COR)) % Walter
timeit(@() methodindex(COR)) % Bruno
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
el 20 de Jul. de 2023
Respuestas (3)
Maybe using eye and repmat
COR = repmat(eye(8),1,1,188);
size(COR)
3 comentarios
aldo
el 20 de Jul. de 2023
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
el 20 de Jul. de 2023
% Generate dummy test data
a = 0.01*rand(2,3,4)
[b,c,d] = size(a);
[I,K] = ndgrid(1:min(b,c),1:d);
a(sub2ind([b,c,d],I,I,K)) = 1;
a
% Generate dummy test data
a = 0.01*rand(2,3,4)
[b,c,d] = size(a);
a(1+(b+1)*(0:min(b,c)-1)'+b*c*(0:d-1)) = 1;
a
Categorías
Más información sobre Region and Image Properties en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!