Accessing cell array entries using arrays

1 次查看(过去 30 天)
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>

采纳的回答

Stephen23
Stephen23 2024-7-1
编辑:Stephen23 2024-7-1
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 个评论
Stephen23
Stephen23 2024-7-1
编辑:Stephen23 2024-7-1
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]}

请先登录,再进行评论。

更多回答(1 个)

Aquatris
Aquatris 2024-7-1
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 个评论
OK
OK 2024-7-1
Thank you! I actually wanted to populate A using the column indices from B (as was resolved in the accepted answer)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by