Suppose a 3-D matrix :
>> a = rand(3,4,2)
a(:,:,1) =
0.1067 0.7749 0.0844 0.8001
0.9619 0.8173 0.3998 0.4314
0.0046 0.8687 0.2599 0.9106
a(:,:,2) =
0.1818 0.1361 0.5499 0.6221
0.2638 0.8693 0.1450 0.3510
0.1455 0.5797 0.8530 0.5132
I use linear indexing to have many element at a time:
>> index1 = [1 ; 2 ; 1 ; 3];
>> index2 = [1 ; 4 ; 2 ; 3];
>> index3 = [1 ; 1 ; 2 ; 1];
>> indices = sub2ind(size(a), index1, index2, index3)
>> a(indices)
ans =
0.1067
0.4314
0.1361
0.2599
I would like to do the same thing, put return all the values of the first dimensions. The size of this dimension may vary. The return should be, in that case:
>> indices = sub2ind(size(a), ??????, index2, index3);
>> a(indices)
ans =
0.1067 0.9619 0.0046 % a(:,1,1)
0.8001 0.4314 0.9106 % a(:,4,1)
0.1361 0.8693 0.5797 % a(:,2,2)
0.0844 0.3998 0.2599 % a(:,3,1)
Any way to do that in MatLab?
1 Answer