Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a colon for indexing in matrices of unknown dimensions

When indexing matrices in MATLAB, can I specify only the first or last n dimensions, and have all others dimensions "selected automatically"?

For example, I am writing a function which takes in an image, and displays it with imshow, which can either display a 3-D color image (e.g 1024×768×3) or a 2-D monochrome array (e.g 1024x768).
My function does not care about how many color channels the image has, imshow will take care of that. All I want to do is pass parameters to select a single region:

imshow(frame(x1:x2, y1:y2, :))

What do I put in place of the last colon to say "include all the others dimensions"?

like image 352
sebf Avatar asked Jun 04 '13 17:06

sebf


2 Answers

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{:})
like image 196
Oleg Avatar answered Nov 15 '22 07:11

Oleg


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);
like image 40
PDBurns Avatar answered Nov 15 '22 05:11

PDBurns