MATLAB: How to find a minimum in this matrix

arrayhuge matrixind2subindexindexinglinear indexingMATLABminminimumnd-arraysub2indsubscript indexingvector direction m...vector direction minimum

Hi all,
I need your help doday because I can not get rid of my problem :
I have a 6D matrix, 'C', filled with costs values. The six dimensions are : speed, acceleration, and 4 'control variables' : U1,U2,U3,U4.
I want to find the position (the value of the control variables) of the minimum cost for each pair of speed and acceleration. The result could be a matrix, attached. If several equal minimums are found, we could keep only one.
The main point is that I run Matlab 2016b, which does not support "vector directions" minimum. The second point is that my 6D 'C' cost matrix is HUUUUUGE and is about 1/100 of my total RAM capacity !
Thank you a lot for your help,
Simon ๐Ÿ™‚

Best Answer

I have no idea how this will compare to using a few loops:
A = randi(999,8,7,6,5,4,3); % fake data in 8x7x6x5x4x3 array.
S = size(A);
B = reshape(A,S(1),S(2),[]);
[M,X] = min(B,[],3); % M = matrix of the minimum values.
[R,C] = ndgrid(1:S(1),1:S(2));
[~,~,U1,U2,U3,U4] = ind2sub(S,sub2ind(size(B),R,C,X))
which gives:
U1 =
3 2 6 4 5 4 3
1 4 2 5 4 5 1
3 5 6 2 2 4 1
4 2 1 4 6 4 3
2 1 4 5 1 4 6
5 1 6 6 5 2 1
6 4 5 5 3 6 1
5 3 2 6 1 3 5
U2 =
1 3 2 5 5 3 1
3 2 1 1 5 4 1
5 5 3 1 5 2 4
5 2 1 4 3 5 2
1 1 5 4 5 5 1
5 1 2 1 3 3 1
3 5 5 1 5 4 5
5 1 2 4 4 3 2
U3 =
4 2 3 4 3 4 4
2 3 4 4 1 4 2
4 3 2 4 1 3 1
4 2 3 3 2 4 2
2 3 2 2 2 4 1
4 2 2 1 3 2 2
3 1 3 3 2 3 1
2 1 3 3 2 2 2
U4 =
3 2 3 2 3 2 2
1 1 1 2 1 1 3
3 2 1 3 1 1 3
1 2 3 3 3 3 3
1 1 2 3 1 3 2
1 1 3 1 3 3 2
3 2 3 3 2 2 1
2 1 1 1 2 1 2
And checking one of them (here I picked row=1 col=2 as an example):
>> M % minimum values for each row/column of A
M =
1 9 1 4 1 1 9
3 4 7 1 3 1 18
1 3 1 5 10 2 3
2 4 2 3 2 7 2
2 1 7 8 4 1 1
4 2 2 3 2 10 2
1 5 1 7 2 6 2
3 5 1 1 2 1 2
๎งป>> A(1,2,2,3,2,2) % A(row,col,U1(row,col),U2(row,col),...)
ans = 9
>> Z = A(1,2,:,:,:,:); % A(row,col,:,:,:,:)
>> min(Z(:))
ans = 9