Matlab syntax (vectorization)

2 vues (au cours des 30 derniers jours)
ConvexHull
ConvexHull le 30 Mar 2020
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 commentaire
Mohammad Sami
Mohammad Sami le 31 Mar 2020
You can use the functions ind2sub and sub2ind to convert between subscripts and linear indexing.

Connectez-vous pour commenter.

Réponses (1)

Dhananjay Kumar
Dhananjay Kumar le 2 Avr 2020
Modifié(e) : Dhananjay Kumar le 2 Avr 2020
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

Catégories

En savoir plus sur Resizing and Reshaping Matrices dans Help Center et File Exchange

Produits


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by