Help finding the min and max of a matrix without using min/max commands
    3 ビュー (過去 30 日間)
  
       古いコメントを表示
    
I'm having trouble trying to find the min and max of this matrix. So far I can only get it to display the min which is -12, but it doesn't display the max at all, it just shows the entire matrix when I try to display the max. Any help is appreciated, thank you.
 mat2=[-1 0 2;7 -4 12;4 8.2 11;-11 0 -12];
n=size(mat2);
max=mat2;
min=mat2;
for i=1:1:n(1);
    for j=1:1:n(2);
        if(mat2(i,j)>max);
            max=mat2(i,j);
        else(mat2(i,j)<min);
            min=mat2(i,j);
        end
    end
end
max 
min
1 件のコメント
  John D'Errico
      
      
 2016 年 4 月 9 日
				For your own sake, NEVER define a variable named min or max, or other existing functions.
If you do, then your next question will be the urgent one, WHY DOES MY CODE THAT TRIES TO USE THE MAX FUNCTION NOT WORK?
採用された回答
  Roger Stafford
      
      
 2016 年 4 月 9 日
        Change the two lines
   max=mat2;
   min=mat2;
to
   max = -inf;
   min = inf;
Note: It is a poor practice to use the terms 'max' and 'min' for variable names, since those are the names for matlab functions.
0 件のコメント
その他の回答 (1 件)
  Andrei Bobrov
      
      
 2016 年 4 月 9 日
        
      編集済み: Andrei Bobrov
      
      
 2016 年 4 月 9 日
  
      mn = mat2(1);
mx = mat2(1);
for ii = 2:numel(mat2)
    if mat2(ii) < mn
        mn = mat2(ii);
        imn = ii;
    elseif mat2(ii) > mx
        mx = mat2(ii);
        imx = ii;
    end
end
without min and max :)
max1 = mat2(sum(bsxfun(@gt,mat2(:),mat2(:)'),2) == numel(mat2)-1);
min1 = mat2(sum(bsxfun(@lt,mat2(:),mat2(:)'),2) == numel(mat2)-1);
1 件のコメント
  ahmed yacine LARDJANE
 2020 年 11 月 30 日
				Hello, 
could you please answer me here? https://fr.mathworks.com/matlabcentral/answers/669058-finding-min-and-max-of-an-element-without-using-builtin-function/
参考
カテゴリ
				Help Center および File Exchange で Resizing and Reshaping Matrices についてさらに検索
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!




