フィルターのクリア

What would be the way to use one 3D array as index for other 3D array?

4 ビュー (過去 30 日間)
Mantas Vaitonis
Mantas Vaitonis 2018 年 7 月 4 日
コメント済み: Mantas Vaitonis 2018 年 7 月 4 日
Hello, I have two 3D arrays a (3x5x4) and o (1x5x4). What I would like to achieve is to use o array as index for a. The struggle is when I use the function below it would take whole o array when creating new array x (1x5x4), maybe anyone has any idea. I thought about pagefun, but it works with only predefined functions.
a=rand(3,5,4)
o= cat(3,[2 5 1 2 4],[2 5 3 1 5],[2 2 2 4 4],[2 3 1 5 4])
x=a(2,o,:)

採用された回答

Stephen23
Stephen23 2018 年 7 月 4 日
The simplest solution is to use a temporary variable:
>> tmp = a(2,:,:);
>> x = tmp(o)
Another option would be to convert the subscript indices into linear indices, but this is not so trivial.
  5 件のコメント
Stephen23
Stephen23 2018 年 7 月 4 日
編集済み: Stephen23 2018 年 7 月 4 日
@Mantas Vaitonis: convert the subscript indices into linear indices:
>> a = rand(3,5,4)
a =
ans(:,:,1) =
0.619297 0.782286 0.293458 0.489529 0.063580
0.727413 0.462825 0.712196 0.129529 0.010375
0.535980 0.625046 0.098377 0.589341 0.623387
ans(:,:,2) =
0.532375 0.927982 0.581526 0.094430 0.486161
0.931640 0.580941 0.182186 0.314561 0.209293
0.826359 0.040024 0.528289 0.704205 0.360965
ans(:,:,3) =
0.225279 0.708014 0.587027 0.020373 0.792127
0.573342 0.530581 0.896023 0.556469 0.471478
0.795015 0.122115 0.109518 0.890492 0.351620
ans(:,:,4) =
0.082299 0.173384 0.587164 0.179035 0.244157
0.527470 0.635292 0.400517 0.953553 0.631803
0.886819 0.880137 0.526968 0.197963 0.232092
>> o = cat(3,[2,5,1,2,4],[2,5,5,3,4],[3,5,4,2,4],[2,1,1,1,4]);
>> S = size(a);
>> [R,~,P] = ndgrid(2,1:S(2),1:S(3)); % 1st input 2 -> row.
>> x = a(sub2ind(S,R,o,P))
x =
ans(:,:,1) =
0.462825 0.010375 0.727413 0.462825 0.129529
ans(:,:,2) =
0.580941 0.209293 0.209293 0.182196 0.314561
ans(:,:,3) =
0.896023 0.471478 0.556469 0.530581 0.556469
ans(:,:,4) =
0.635292 0.527470 0.527470 0.527470 0.953553
Mantas Vaitonis
Mantas Vaitonis 2018 年 7 月 4 日
Yes this is exactly what I need, thank you.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by