フィルターのクリア

Accessing cell array entries using arrays

30 ビュー (過去 30 日間)
OK
OK 2024 年 7 月 1 日 9:05
コメント済み: OK 2024 年 7 月 1 日 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>

採用された回答

Stephen23
Stephen23 2024 年 7 月 1 日 9:12
編集済み: Stephen23 2024 年 7 月 1 日 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 件のコメント
OK
OK 2024 年 7 月 1 日 9:15
Thank you!
Stephen23
Stephen23 2024 年 7 月 1 日 9:25
編集済み: Stephen23 2024 年 7 月 1 日 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]}

サインインしてコメントする。

その他の回答 (1 件)

Aquatris
Aquatris 2024 年 7 月 1 日 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 件のコメント
OK
OK 2024 年 7 月 1 日 9:35
Thank you! I actually wanted to populate A using the column indices from B (as was resolved in the accepted answer)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by