Matlab syntax (vectorization)

2 次查看(过去 30 天)
ConvexHull
ConvexHull 2020-3-30
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 CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by