Creating submatrix with variable indexing
조회 수: 6 (최근 30일)
이전 댓글 표시
I have a larger multidimensional array of data that I want to grab a section of, but the data I'm interested in extracting starts at a different index depending on the vector. I know the values the starting index and ending index of the data i want to extract, but I'm not sure how to get matlab to do create this new matrix (the data is of a fixed length). Due to the data size I do not want to use nested for loops, which would have made this easy.
Thanks!
(edit, one approach that hasn't worked is the creation of a 1s and 0s matrix multiplied by the original data set and then removing the zeros. The data of interest contains zeros, so using a nonzeros approach led to problems).
댓글 수: 3
Turlough Hughes
2020년 2월 22일
You're potentially very close to getting this. If your logical matrix is an a x b x c array with true values at indices you wish to extract then instead of multiplying the logical matrix you should use the logical matrix as the index itself. Look up logical indexing in matlab. .
답변 (1개)
Rik
2020년 2월 22일
The code below isn't elegant, but it should do what you want. The example is for just 2x2xN. Despite the name, the slow method is faster for larger matrices, because the JIT can optimize a lot there.
data=rand(2,2,1500);
inds=randi(size(data,3)-1000,size(data,1),size(data,2));
[X,Y,Z]=ndgrid(1:size(data,1),1:size(data,2),1:1000);
Z=Z+inds;
ind=sub2ind(size(data),X,Y,Z);
new_fast=data(ind);
new_slow=zeros(size(X));
for x=1:size(data,1)
for y=1:size(data,2)
new_slow(x,y,:)=data(x,y,inds(x,y)+(1:1000));
end
end
%test if the results are the same, should return 0 (or close to it)
max(abs(new_fast(:)-new_slow(:)))
댓글 수: 1
Rik
2020년 2월 26일
Did my answer solve your question? If not, feel free to comment with your remaining issues.
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!