Hello,
I have a 3D matrix C of size 2N×N×N and I need to take the diagonal slices of C and construct another 2D and 1D arrays with it. Like
D(i,j)=C(i,i,j)
D(i,j)=C(i,j,j)
D(i)=C(i,i,i)
And vice versa. If I have 1D and 2D arrays, how can I add them as diagonal slices to 3D matrix?
Is there a way to do it avoiding loops?

댓글 수: 2

James Tursa
James Tursa 2020년 9월 25일
Please show small complete examples showing input(s) and desired output(s).
Mark Lyubarov
Mark Lyubarov 2020년 9월 25일
편집: Mark Lyubarov 2020년 9월 25일
yes, it goes like this. For example, let C be random.
N=10;
C=rand(2*N,N,N);
D1=zeros(2*N,N);
for i=1:2*N
for j=1:N
D1(i,j)=C(i,j,j);
end
end
D1
or
D2=zeros(2*N,N)
for i=1:N
for j=1:N
D2(i,j)=C(i,i,j);
D2(i+N,j)=C(i+N,i,j);
end
end
the second is a little bit more tricky, but if I understand how to do first one, I can always split C into 2 qubic arrays and work with it.
I am new here, I don't know how to insert output, sorry. But I suppose now it is a little bit more clear.
So can I get such D1,D2 matrices without using loops?

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

답변 (2개)

Ameer Hamza
Ameer Hamza 2020년 9월 25일
편집: Ameer Hamza 2020년 9월 25일

1 개 추천

The question is not entirely clear, so the following is my guess, but such a problem can be solved using sub2ind().
C = % 2N*N*N
rows = 1:2*N;
cols = 1:N;
pages = 1:N;
idx = sub2ind(size(C), repelem(rows, 1, N), repmat(cols, 1, 2*N), repmat(pages, 1, 2*N));
D = reshape(C(idx), N, 2*N).'

댓글 수: 2

Mark Lyubarov
Mark Lyubarov 2020년 9월 25일
Thank you very much, it works! And do you know if it is faster than with loops?
Ameer Hamza
Ameer Hamza 2020년 9월 26일
Try using tic and toc to find the execution time in both cases. I guess the vectorized will at least be equivalent, if not faster, then the looped version.

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

Bruno Luong
Bruno Luong 2020년 9월 26일
편집: Bruno Luong 2020년 9월 26일

0 개 추천

[I,J] = ndgrid(1:N);
D1 = zeros(2*N,N);
D1(sub2ind(size(D1),I,J)) = C(sub2ind(size(C),I,J,J));
D2 = zeros(2*N,N);
D2(sub2ind(size(D2),I,J)) = C(sub2ind(size(C),I,I,J));
D2(sub2ind(size(D2),I+N,J)) = C(sub2ind(size(C),I+N,I,J));

카테고리

도움말 센터File Exchange에서 Sparse Matrices에 대해 자세히 알아보기

제품

릴리스

R2019a

질문:

2020년 9월 25일

편집:

2020년 9월 26일

Community Treasure Hunt

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

Start Hunting!

Translated by