필터 지우기
필터 지우기

function min() using loop or nested loop

조회 수: 6 (최근 30일)
Juan Zegarra
Juan Zegarra 2019년 4월 28일
답변: Nithin Kumar 2023년 3월 3일
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
dpb
dpb 2019년 4월 28일
  1. Use counted for loops; much easier if don't have to compute the indices yourself...
  2. Initialize the outputs of the size to be returned before starting the loop...
  3. Study what the builtin function returns for some sample cases so you really understand what you're trying to return..
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...

댓글을 달려면 로그인하십시오.

답변 (1개)

Nithin Kumar
Nithin Kumar 2023년 3월 3일
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:");
Minimum values:
disp(min_vals);
3 0 2
disp("Indices of minimum values:");
Indices of minimum values:
disp(min_idxs);
1 2 3
I hope this code helps you resolve the issue you are encountering.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by