필터 지우기
필터 지우기

Vectorized nD diag loop

조회 수: 2 (최근 30일)
Javier Fernandez
Javier Fernandez 2022년 7월 5일
댓글: Javier Fernandez 2022년 7월 5일
Hello everyone,
I have the following loop which I would want to have vectorized.
I know the diag() command cannot be used in nD arrays (n>2), so is there an alternative way to vectorize the loop?
n = 10; m = 15;
A = rand(4,n,m);
for i = 1:n
for j = 1:m
B(:,:,i,j) = diag(A(:,i,j));
end
end
Thanks in advance!

채택된 답변

Chunru
Chunru 2022년 7월 5일
n = 400; m = 500;
A = rand(4,n,m);
B = zeros(4,4,n,m); % initialize to speed up
tic
for i = 1:n
for j = 1:m
B(:,:,i,j) = diag(A(:,i,j));
end
end
toc
Elapsed time is 0.351235 seconds.
% Vectorized
tic
C = zeros(4*4,n*m);
C(1:5:16, :) = A(1:4, :);
C =reshape(C, [4, 4, n, m]);
toc
Elapsed time is 0.015569 seconds.
isequal(B, C)
ans = logical
1
  댓글 수: 1
Javier Fernandez
Javier Fernandez 2022년 7월 5일
This is what I was looking for! Thank you very much for your kind help.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by