Extract X number of elements in 3D matrix based on another matrix

조회 수: 2 (최근 30일)
Vesp
Vesp 2017년 6월 20일
편집: Andrei Bobrov 2017년 6월 23일
Hello,
I have a 3D Matrix A (3x3x5) that is sorted in descending order and another Matrix B (3x3) which has the first X number of elements in Matrix A that I would like to extract and store in a blank matrix C (3x3x5). Matrix B has different first elements to extract, so I would like the rest of the elements in the 3D matrix C to be zero if there isn't anything copied from A. Let's say there are 2 values that I want to extract at element 1x1x1:5, then cell 1x1x1:2 in Matrix C will be 10; 5; 0; 0;0
Example of Matrix A and B: A=randi(10,3,3,5); B=[NaN 2 1; 2 NaN 2;NaN 4 3];
Thank you for the help.

채택된 답변

Andrei Bobrov
Andrei Bobrov 2017년 6월 20일
편집: Andrei Bobrov 2017년 6월 20일
A=randi(10,3,3,5);
B=[NaN 2 1; 2 NaN 2;NaN 4 3];
[m,n,k] = size(A);
B(isnan(B)) = 0;
out = permute(reshape((1:k)'*ones(1,m*n) <= B(:)',[],m,n),[2,3,1]).*A; %2016b and later
out = permute(reshape(bsxfun(@le,(1:k)'*ones(1,m*n),B(:)'),[],m,n),[2,3,1]).*A; %2016a and earlier
  댓글 수: 2
Vesp
Vesp 2017년 6월 20일
Thank you very much for your help Andrei! This is useful code to learn for the future :)
Vesp
Vesp 2017년 6월 23일
편집: Andrei Bobrov 2017년 6월 23일
Andrei I was wondering if you could break down exactly what this code does. It is extracting correctly, but for some reason when I apply it to my code I am not getting the correct answer.
The main idea of my code is to sort total IVT and then sort the x and y component, then use this piece of code to extract the "top N" values defined in a matrix (in this example Matrix B). When I calculate the magnitude of the separate x and y components they do not match that of the total IVT. There is a difference of up to 50 between some of the elements.
If it helps to see the entire code I have asked a question in the following link. My effort to figure this out was of no avail. I appreciate the help and time.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by