Borrar filtros
Borrar filtros

Accessing cell array entries using arrays

30 visualizaciones (últimos 30 días)
OK
OK el 1 de Jul. de 2024 a las 9:05
Comentada: OK el 1 de Jul. de 2024 a las 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>

Respuesta aceptada

Stephen23
Stephen23 el 1 de Jul. de 2024 a las 9:12
Editada: Stephen23 el 1 de Jul. de 2024 a las 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 comentarios
OK
OK el 1 de Jul. de 2024 a las 9:15
Thank you!
Stephen23
Stephen23 el 1 de Jul. de 2024 a las 9:25
Editada: Stephen23 el 1 de Jul. de 2024 a las 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]}

Iniciar sesión para comentar.

Más respuestas (1)

Aquatris
Aquatris el 1 de Jul. de 2024 a las 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 comentario
OK
OK el 1 de Jul. de 2024 a las 9:35
Thank you! I actually wanted to populate A using the column indices from B (as was resolved in the accepted answer)

Iniciar sesión para comentar.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Productos


Versión

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by