フィルターのクリア

function min() using loop or nested loop

17 ビュー (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by