Effacer les filtres
Effacer les filtres

Accessing cell array entries using arrays

30 vues (au cours des 30 derniers jours)
OK
OK le 1 Juil 2024 à 9:05
Commenté : OK le 1 Juil 2024 à 9:35
I have a multi-dimensional cell array and matrix, whose columns correspons to indices of the cell array. I want to populate the cells with arrays that correspond to the indices of the columns that refer to the given cell.
Minimal example:
A=cell(2,2);
B=[1 2 2 1 1; 2 1 2 1 2]
B = 2x5
1 2 2 1 1 2 1 2 1 2
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
A{1,1}=[4];
A{1,2}=[1,5];
A{2,1}=[2];
A{2,2}=[3]
A = 2x2 cell array
{[4]} {[1 5]} {[2]} {[ 3]}
I'm trying to do this automatically by looping over the columns of the matrix B, but I can't figure out how to extract the entries of the array without keeping the array form. Calling neither
A(B(:,1))
ans = 2x1 cell array
{[4]} {[2]}
nor
A{B(:,1)}
ans = 4
ans = 2
produces the correct entry
A{1,2}
ans = 1x2
1 5
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Réponse acceptée

Stephen23
Stephen23 le 1 Juil 2024 à 9:12
Modifié(e) : Stephen23 le 1 Juil 2024 à 9:13
B = [1,2,2,1,1; 2,1,2,1,2];
V = 1:size(B,2);
A = accumarray(B.',V(:),[],@(m){m.'})
A = 2x2 cell array
{[4]} {[1 5]} {[2]} {[ 3]}
A{1,2}
ans = 1x2
1 5
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
  2 commentaires
OK
OK le 1 Juil 2024 à 9:15
Thank you!
Stephen23
Stephen23 le 1 Juil 2024 à 9:25
Modifié(e) : Stephen23 le 1 Juil 2024 à 9:29
If you really want to use a loop:
A = cell(2,2);
B = [1,2,2,1,1; 2,1,2,1,2];
for k = 1:size(B,2)
C = num2cell(B(:,k));
A{C{:}} = [A{C{:}},k];
end
A
A = 2x2 cell array
{[4]} {[1 5]} {[2]} {[ 3]}
Or:
A = cell(2,2);
for k = 1:size(B,2)
A{B(1,k),B(2,k)} = [A{B(1,k),B(2,k)},k];
end
A
A = 2x2 cell array
{[4]} {[1 5]} {[2]} {[ 3]}

Connectez-vous pour commenter.

Plus de réponses (1)

Aquatris
Aquatris le 1 Juil 2024 à 9:21
I think you want to use B columns as indeces to extract info from A, so:
A=cell(2,2);
B=[1 2 2 1 1;
2 1 2 1 2]
B = 2x5
1 2 2 1 1 2 1 2 1 2
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
A{1,1}=[4];
A{1,2}=[1,5];
A{2,1}=[2];
A{2,2}=[3];
for i = 1:size(B,2)
fprintf('The B(:,%d)= [%d, %d]'' and A(B(:,%d)'') is: ',i,B(:,i),i)
disp(A{B(1,i),B(2,i)})
end
The B(:,1)= [1, 2]' and A(B(:,1)') is:
1 5
The B(:,2)= [2, 1]' and A(B(:,2)') is:
2
The B(:,3)= [2, 2]' and A(B(:,3)') is:
3
The B(:,4)= [1, 1]' and A(B(:,4)') is:
4
The B(:,5)= [1, 2]' and A(B(:,5)') is:
1 5
  1 commentaire
OK
OK le 1 Juil 2024 à 9:35
Thank you! I actually wanted to populate A using the column indices from B (as was resolved in the accepted answer)

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by