n dimensional array section
古いコメントを表示
Ok, lets say that I have a code where I can have an array:
A = randi([0,9],4,4);
and I want to access the last two columns and rows:
B = A(2:end,2:end);
Now I have the same thing but with 3 dimensions:
A = randi([0,9],4,4,4);
B = A(2:end,2:end,2:end);
Is there any way that I can write both cases in a single generic one?, I was trying to do something like:
n = 2; % or 3 or whatever
dims = 4*ones(1,n);
A = randi([0,9],dims);
B = A( 2*ones(1,n):end); % THIS WONT WORK.
I don't know if I explained what I wan't. Please let me know if you need more precise explanation. Thank you
回答 (2 件)
KSSV
2018 年 10 月 22 日
Read about sub2ind
n = 2; % or 3 or whatever
dims = 4*ones(1,n);
A = randi([0,9],dims);
[I,J] = meshgrid(2:4,2:4) ;
idx = sub2ind(size(A),I,J)' ;
B = A(idx);
Use a comma-separated list.
n = 2; % or 3 or whatever
dims = 4*ones(1,n);
A = randi([0,9],dims) % Leaving the semicolon off for checking purposes
inds = cell(1, n);
for dim = 1:n
inds{dim} = (size(A, dim))+(-1:0); % [end-1, end] in that dimension
end
B = A(inds{:})
カテゴリ
ヘルプ センター および File Exchange で Programming についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!