I currently have the following cell :
G=cell(4,2)
Each sell has a 2x1 double
Example :
[100;200] [20;60]
[100;300] [20;90]
[200;300] [60;90]
[] [] [] []
How can I identify which cell has the minimum value, (where the values compared are in the SECOND column) so that the addition is between 20;60 20;90 and 60;90 ?
I started typing out a code but got stuck :
for k=1:(4)
add(k)=sum(cell2mat(G(k+4)))
end
(...Find a way to know which cell gave the minimum off `add` using min(add)...)
But then I don't how to identify which cell has the minimum .. The answer I'm looking for should indicate that the minimum value is at Column 2 Row 1 of cell G and hence : 20;60
G[{:}]
will arrange (column-wise) the cell array to a 2D matrix (lines corresponding to the first and second element of each cell entry
ans =
100 100 200 20 20 60
200 300 300 60 90 90
You can then apply min
accordingly to obtain the minimum value and a linear index on the cell, e.g.:
[minVal, minIndex] = min([G{:}], [], 2);
Update: Since the sum of elements is defined as minimum (L1 norm), you can use cellfun to detect empty entries and sum in each, before applying min
over the resulting array:
indexEmpty = cellfun(@isempty, G) % find empty entries of G
sumG = cellfun(@sum, G) % apply sum on each entry of G
sumG(indexEmpty) = nan; % set empty entries to NaN (exclude from min)
[minVal, minIndex] = min(sumG(:)); % return min and its location in sumG (and G)
Result: G{minIndex}
ans =
20
60
The linear index minIndex
can be translated to array subscripts using ind2sub.
[i,j] = ind2sub(size(G), minIndex);
In this way you can index the array both using G{minIndex}
(i.e., 5) and G{i,j}
(i.e., 1,2).