max of two arrays one being empty returns the empty array

조회 수: 6 (최근 30일)
Harish Dhanasekaran Velayutha Rajan
답변: Walter Roberson 2024년 10월 22일
i need to find maximum of elements of two arrays. if one is empty, Max function always returns the empty one. For ex: A=[]; B=[5]; max(A,B) returns [].
How to solve the problem ?

답변 (2개)

BhaTTa
BhaTTa 2024년 10월 22일
편집: Walter Roberson 2024년 10월 22일
Hey @Harish Dhanasekaran Velayutha Rajan, I assume that if one of the array among 'A' or 'B' is empty you need to return [], or else you need to return maximum element, below I have attached the logic for the same, please take it as a reference and implement your function accordingly:
% Define the arrays
A = [3,4,6,7];
B = [5];
% Check if either array is empty and handle accordingly
if isempty(A) || isempty(B)
maxValue = [];
else
% Both arrays are non-empty, return the maximum of both
maxValue = max(max(A), max(B));
end
% disp(maxValue); you can enclose the code block inside a function and return the maxValue.
Hope it helps.

Walter Roberson
Walter Roberson 2024년 10월 22일
This is the way that max() is defined: the maximum of an empty array is an empty array.
A=[]; B=[5];
max(A,B)
ans = []
max(B,A)
ans = []
However, if the second array is empty and further options were provided, then it is treated as a special syntax and takes the maximum of the first array subject to the options.
max(B,A,1)
ans = 5
max(A,B,1)
Error using max
Specifying the operating dimension is not supported for two input arrays.

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by