- Use counted for loops; much easier if don't have to compute the indices yourself...
- Initialize the outputs of the size to be returned before starting the loop...
- Study what the builtin function returns for some sample cases so you really understand what you're trying to return..
function min() using loop or nested loop
    6 views (last 30 days)
  
       Show older comments
    
Write e acode for the MatLab function min() that will have a vector or matrix argument and will return the minimun and index of the minimun for each column of the vector or matrix. This code must use a loop or nested loop. 
I've done this so far but I'm having some issues running it.
function [Min,Index]=Max(matrix)
[row,col]=size(matrix)
r=1
c=1
while r < col
    Max(c)=matrix(1,c)
    Index(c)=1
    while r < row
        if matrix(r,c)<= Max(c)
            Max(c)= matrix(r,c);
            Index(c)=c;
        end
        r=r+1
    end
    c=c+1
end
1 Comment
  dpb
      
      
 on 28 Apr 2019
				Philosophical rumination:  I'm somewhat in agreement with some other respondents here that homework requiring to use looops to duplicate builtin functionality may teach improper use of ML by not using its vectorized functions but then again, to teach the general ideas of how to write general-purpose programs, learning looping constructs is imperative...
Answers (1)
  Nithin Kumar
    
 on 3 Mar 2023
        Hi Juan,  
I understand that you are trying to implement "min()" using loop or nested loop and facing an issue while running the code. 
I am attaching a code below which can be used to find an element with the minimum value in each column of a matrix and the index associated with that element.
A = [3, 5, 6; 8, 0, 4; 9, 7, 2];
[m, n] = size(A);
min_vals = zeros(1, n);
min_idxs = zeros(1, n);
for j = 1:n
    min_val = A(1,j);
    min_idx = 1;
    for i = 2:m
        if A(i,j) < min_val
            min_val = A(i,j);
            min_idx = i;
        end
    end
    min_vals(j) = min_val;
    min_idxs(j) = min_idx;
end
disp("Minimum values:");
disp(min_vals);
disp("Indices of minimum values:");
disp(min_idxs);
I hope this code helps you resolve the issue you are encountering.
0 Comments
See Also
Categories
				Find more on Loops and Conditional Statements in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

