Using a colon to index in matrices of unknown dimensions

When indexing matrices in MATLAB, you can specify only the first or last n dimensions, and all other dimensions are "automatically selected"?

For example, I am writing a function that takes an image and displays it using imshow , which can display a three-dimensional color image (e.g. 1024Γ—768Γ—3 ) or a two-dimensional monochrome array (e.g. 1024x768).
My function does not care about how many color channels an image has, imshow will take care of that. All I want to do is pass parameters to select one region:

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

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

+5
source share
2 answers

You can use the comma-separated extension along with the ':' index.

Suppose your input is:

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

To get only the first 2:

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

To get the last 3:

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

What can be generalized with:

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

After Oleg’s answer, here is a function that will work if you choose from the first few dimensions. If other dimensions are needed, I think you can see how to change them.

 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); 
+1
source

Source: https://habr.com/ru/post/957995/


All Articles