Clear Filters
Clear Filters

Accessing cell array entries using arrays

30 views (last 30 days)
OK
OK on 1 Jul 2024 at 9:05
Commented: OK on 1 Jul 2024 at 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>

Accepted Answer

Stephen23
Stephen23 on 1 Jul 2024 at 9:12
Edited: Stephen23 on 1 Jul 2024 at 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 Comments
Stephen23
Stephen23 on 1 Jul 2024 at 9:25
Edited: Stephen23 on 1 Jul 2024 at 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]}

Sign in to comment.

More Answers (1)

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

Sign in to comment.

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!