Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
651 views
in Technique[技术] by (71.8m points)

matlab - 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"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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{:})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...