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 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