I am attempting to find the maximum value and its location in multidimensional array using Matlab. There are functions findMax3, findMax4, findMax5 and findMax6 for dealing with different dimension cases.
The experimental implementation
function [maxNum, v1, v2, v3] = findMax3(input3d)
maxNum = max(input3d, [], 'all');
index = find(input3d(:) == maxNum );
%The dimensions of the array needs to be fed as an input to ind2sub function
[v1, v2, v3] = ind2sub(size(input3d),index);
end
function [maxNum, v1, v2, v3, v4] = findMax4(input4d)
maxNum = max(input4d, [], 'all');
index = find(input4d(:) == maxNum );
%The dimensions of the array needs to be fed as an input to ind2sub function
[v1, v2, v3, v4] = ind2sub(size(input4d),index);
end
function [maxNum, v1, v2, v3, v4, v5] = findMax5(input5d)
maxNum = max(input5d, [], 'all');
index = find(input5d(:) == maxNum );
%The dimensions of the array needs to be fed as an input to ind2sub function
[v1, v2, v3, v4, v5] = ind2sub(size(input5d),index);
end
function [maxNum, v1, v2, v3, v4, v5, v6] = findMax6(input6d)
maxNum = max(input6d, [], 'all');
index = find(input6d(:) == maxNum );
%The dimensions of the array needs to be fed as an input to ind2sub function
[v1, v2, v3, v4, v5, v6] = ind2sub(size(input6d),index);
end
Test cases
% Unit tests for findMax function
%% Three-dimensional case
sizeNum = 10;
TestArray = zeros(sizeNum, sizeNum, sizeNum);
TestArray(1, 2, 3) = 1;
[maxNum, v1,v2,v3] = findMax3(TestArray)
%% Four-dimensional case
sizeNum = 10;
TestArray = zeros(sizeNum, sizeNum, sizeNum, sizeNum);
TestArray(1, 2, 3, 4) = 1;
[maxNum, v1, v2, v3, v4] = findMax4(TestArray)
%% Five-dimensional case
sizeNum = 10;
TestArray = zeros(sizeNum, sizeNum, sizeNum, sizeNum, sizeNum);
TestArray(1, 2, 3, 4, 5) = 1;
[maxNum, v1, v2, v3, v4, v5] = findMax5(TestArray)
%% Six-dimensional case
sizeNum = 10;
TestArray = zeros(sizeNum, sizeNum, sizeNum, sizeNum, sizeNum, sizeNum);
TestArray(1, 2, 3, 4, 5, 6) = 1;
[maxNum, v1, v2, v3, v4, v5, v6] = findMax6(TestArray)
All suggestions are welcome.