Using a colon for indexing in matrices of unknown dimensions

血红的双手。 提交于 2019-11-29 11:01:18

You can use comma-separated-list expansion together with the ':' indexing.

Suppose your input is:

A = rand([7,4,2,3]);

To retrieve only first 2:

cln = {':', ':'};
A(cln{:})

To retrieve the last 3:

cln = {1, ':', ':', ':'};
A(cln{:})

Which can be generalized with:

sten            = 2:3;    % Which dims to retrieve
cln(1:ndims(A)) = {1};
cln(sten)       = {':'};
A(cln{:})

Following from Oleg's answer, here is a function that will work if you are selecting from several of the first dimensions. If other dimensions are needed, I think you can see how to modify.

function [dat] = getblock2(dat, varargin)
%[dat] = getblock(dat, varargin) select subarray and retain all others
%                                unchanged
%dat2 = getblock(dat, [1,2], [3,5]) is equivalent to
%       dat2 = dat(1:2, 3:5, :, :, :) etc.
%Peter Burns 4 June 2013

arg1(1:ndims(dat)) = {':,'};
v = cell2mat(varargin);
nv = length(v)/2;
v = reshape(v,2,nv)';
for ii=1:nv
    arg1{ii} = [num2str(v(ii,1)),':',num2str(v(ii,2)),','];
end
arg2 = cell2mat(arg1);
arg2 = ['dat(',arg2(1:end-1),')'];
dat = eval(arg2);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!