accessing indexed values in a 3D array with a logical index

I have 3D array of temperature data that looks like this:
Z = rand(3,4,8);
It contains 8 slices of data on 3*4 grid. I have a logical array which is an index to a set of values on each of the 8 slices like this:
ind = logical(randi(2, [3 4]) - 1)
How to I create a new matrix which is the 3D and contains the temp data from Z for ind on each of the slices.
My Z matrix is actally 814*1294*40 and looking at other answers there should be a way to do this; however I am stumped.

 채택된 답변

Walter Roberson
Walter Roberson 2020년 7월 24일
ind = repmat(ind, 1, 1, size(Z,3));
Z(ind)
However, this will give you a vector of results.
How to I create a new matrix which is the 3D and contains the temp data from Z for ind on each of the slices.
That is a problem, because when you select values for each slice, you get holes, and there is no way to create arrays with holes.
You could reshape Z(ind) to [], 1, size(Z,3) which would give you a vector for each layer.

댓글 수: 7

Thanks for your assitance Walter. I am struggling to understand how a vector for each layer will help?
What would you ideally like it to look like when you had a 3D matrix which "contains the temp data from Z for ind on each of the slices", considering that not all locations in the slice are selected ?
I am trying to take the data from large grid of model data and extract a portion in a polygon 250km either side of a tropical cyclone, track and 100km along the track. My aim is to visualise the temp with depth, and be able to see how it changes as the cyclones passes over.
Is it correct that you are intending to extract a cuboid? If so then do not use logical indexing for that, use vectors
Z(first_x : last_x, first_y : last_y, :)
The result would be a cuboid.
Belinda Finlay
Belinda Finlay 2020년 7월 24일
편집: Belinda Finlay 2020년 7월 24일
Thanks Walter, now I need to work out how to get those values (first_x: last_x etc). I am very grateful for your assistance.
Let ind be the rectangular 2D mask that you had from before. Then
mask = any(ind,1);
first_col = find(mask,1);
last_col = find(mask,1,'last');
mask = any(ind,2);
first_row = find(mask,1);
last_row = find(mask,1,'last');
selected_area = Z(first_row : last_row, first_col : last_col, :);
I am extremely grateful for your assistance Walter - I could hug you.

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

추가 답변 (0개)

카테고리

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

제품

릴리스

R2019b

질문:

2020년 7월 24일

댓글:

2020년 7월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by