0

Let's say I have a 3x3x3 Matlab array with members 1 to 27

a=reshape(1:27, [3 3 3])

I would like to create a subset of this with a syntax like

b=a(range1,range2,range3)

where for range1=range2=range3=1:2 I would get the members b(1,1,1) and b(2,2,2). i.e

b= [1 14]

Is it possible to do this just with indexing and without any functions (e.g. diag)? Thanks...

3
  • @Parag, sub2ind requires same size vectors for ranges. For example b=a(sub2ind(size(a),range1,range2,1:3)). That's why I am looking for doing it only with the indices... Commented Mar 15, 2013 at 23:53
  • @Molly please see my comment to Parag above... Commented Mar 15, 2013 at 23:55
  • range1, range2, and range3 have to be the same size because each corresponds to a dimension of the matrix a. For example, if range1 = [x1,x2,x3], range2 = [y1,y2,y3] and range3 = [z1,z2,z3] the values obtained will be a(x1,y1,z1), a(x2,y2,z2) and a(x3,y3,z3). So it wouldn't make sense for this function to take different sized vectors. In the example in your comment, what to do expect the answer to be? Commented Mar 16, 2013 at 1:50

2 Answers 2

1

It can be done with sub2ind function as follows:

b=a(sub2ind(size(a),range1,range2,range3)) ans: b=[1 14] 
Sign up to request clarification or add additional context in comments.

2 Comments

sub2ind requires same size vectors for ranges. For example b=a(sub2ind(size(a),range1,range2,1:3)). That's why I am looking for doing it only with the indices...
If they are of same size, say 1:2, 1:2, 1:3, then how will you decide subscripts. Because when they are of equal size 1:2, subscripts will be (1,1,1) and (2,2,2)
1

The indexing can be done using sub2ind,

a(sub2ind(size(a),[1:2],[1:2],[1:2])) 

if you want to avoid all functions, you could calculated the linear indices yourself...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.