Matlab syntax (vectorization)

2 ビュー (過去 30 日間)
ConvexHull
ConvexHull 2020 年 3 月 30 日
編集済み: Dhananjay Kumar 2020 年 4 月 2 日
Dear all,
i have a simple question that's been bothering me for a while:
For example there is a data array A of size
[size_a,size_b,size_c]=size(A);
and a logical array B with size
[size_a,size_b]=size(B);
Is it possible to query the first two dimensions of Array A with array B without reshaping?
Suppose i want to do something like
C(:,:)=A(B(:),:);
which does not work. Solution would be
D=reshape(A,[size_a*size_b,size_c]);
C(:,:)=D(B(:),:);
Regards
  1 件のコメント
Mohammad Sami
Mohammad Sami 2020 年 3 月 31 日
You can use the functions ind2sub and sub2ind to convert between subscripts and linear indexing.

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

回答 (1 件)

Dhananjay Kumar
Dhananjay Kumar 2020 年 4 月 2 日
編集済み: Dhananjay Kumar 2020 年 4 月 2 日
You should note that logical indexing would select not all the elements from a row(or column) from an array, and that should result in heterogenous array. But MATLAB arrays are homegenous.
So if you do logical indexing, the resulting array flattened and a column of elemnts is returned by MATLAB:
>> a = [1 4 5; 2 0 5];
>> b = a(logical([1 0 0; 1 1 1]))
b =
1
2
0
4
....
Now I will demonstrate the solution you need for your purpose.
You have:
a =
1 4 5
2 0 4
Now do this
>> a2 = num2cell(a)
a2 =
2×3 cell array
{[1]} {[4]} {[5]}
{[2]} {[0]} {[4]}
>> a3 = a2(logical([1 0 0; 1 1 1]))
a3 =
4×1 cell array
{[1]}
{[2]}
{[0]}
{[4]}
Now you can reshape the above 1-dimensional cell-array to a 2x2 cell-array:
>> a4 = reshape(a3, 2,2)
a4 =
2×2 cell array
{[1]} {[0]}
{[2]} {[4]}
Now here is a small hack (there is no function named cell2array) :
>> a5 = table2array(cell2table(a4))
a5 =
1 0
2 4
You can merge all the steps above to make 2 commands:
>> a2 = num2cell(a);
>> a5 = table2array(cell2table(reshape(a2(logical([1 0 0; 1 1 1])),2,2)))
a5 =
1 0
2 4

カテゴリ

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

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by