accessing indexed values in a 3D array

3 ビュー (過去 30 日間)
Chad Greene
Chad Greene 2015 年 7 月 27 日
コメント済み: Chad Greene 2015 年 7 月 27 日
I have a 3D array of temperature data that looks like this:
Z = rand(3,4,8);
It contains 8 slices of data on a 3x4 grid. For each point in the 3x4 grid I have an index that correspond to a slice the third dimension:
ind = randi(8,[3 4])
How do I create a 3x4 surface of values in Z given by the indices ind? I could do it manually like this:
s(1,1) = Z(1,1,ind(1,1));
s(1,2) = Z(1,2,ind(1,2));
s(1,3) = Z(1,3,ind(1,3));
...
s(3,4) = Z(3,4,ind(3,4));
But my Z matrix is 500x500x100, so doing it manually is out of the question. I'm sure I can avoid a loop here somehow.

採用された回答

David Young
David Young 2015 年 7 月 27 日
[rows, cols] = ndgrid(1:size(Z,1), 1:size(Z,2));
Zindex = sub2ind(size(Z), rows, cols, ind);
s = Z(Zindex);
  1 件のコメント
Chad Greene
Chad Greene 2015 年 7 月 27 日
This is perfect, thank you!

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2015 年 7 月 27 日
Zs = size(Z);
S = zeros(Zs(1), Zs(2));
ind_offset = (ind - 1) * Zs(1) * Zs(2) + (1:numel(S));
S(1:numel(S)) = Z(ind_offset);
  2 件のコメント
Walter Roberson
Walter Roberson 2015 年 7 月 27 日
I made a mistake in the above. Also after seeing David's perfectly workable answer I would improve mine:
Zs = size(Z);
ind_offset = (ind - 1) * Zs(1) * Zs(2) + reshape(1:Zs(1)*Zs(2),Zs(1),Zs(2));
S = Z(ind_offset);
Chad Greene
Chad Greene 2015 年 7 月 27 日
Thanks Walter!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeGPU Computing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by