How do i call function with three output arguments?
古いコメントを表示
I have an assignment to write a function which returns the minimum value of the element in the matrix and his index . If function is called with two output arguments , it is necessary to return the minimum value and his linear index If the function is called with three output arguments , also min but with his matrix index. Also i cannot use syntax such as min and others. Problem is that he finds min but he sees only firs value if there's more than one min and i cannot get those linear and matrix indexes.
function [m, v, k] = minimum(A)
m = A(1,1);
v = 1;
k=1;
for i = 2: size(A,1)
for j = 2 : size(A,2)
if A(i,j) < m
m = A(i,j);
v = i;
k=j;
end
end
end
if nargout == 2
v = (k - 1) * size(A,1) + v;
end
if nargout==3
k=ceil(v/size(A,1));
v=v-(k-1)*size(A,1);
end
2 件のコメント
Azzi Abdelmalek
2016 年 5 月 7 日
I am not getting your problem
Azzi Abdelmalek
2016 年 5 月 7 日
編集済み: Azzi Abdelmalek
2016 年 5 月 7 日
What is N in your program?
N=size(A,1)
回答 (2 件)
Azzi Abdelmalek
2016 年 5 月 7 日
You omit to define N
N=size(A,1)
and your first for loop should begin at k=1
for i = 1: size(A,1)
3 件のコメント
Beginner
2016 年 5 月 7 日
Azzi Abdelmalek
2016 年 5 月 7 日
編集済み: Azzi Abdelmalek
2016 年 5 月 7 日
If you are looking for all min value, you can use min function with another line of code.
val=min(y)
[ix,iy]=find(y==val)
Image Analyst
2016 年 5 月 7 日
He said "Also i cannot use syntax such as min and others."
function [minValue, index1, index2] = minimum(A)
minValue = A(1, 1);
index1 = [];
index2 = [];
for i2 = 1:size(A, 2)
for i1 = 1:size(A, 1)
if A(i1, i2) < minValue
minValue = A(i1, i2);
index1 = i1; % Remember new indices
index2 = i2;
elseif A(i1, i2) == minValue % Append to indices
index1 = cat(2, index1, i1);
index2 = cat(2, index2, i2);
end
end
end
if nargout == 2
index1 = index1 + (index2 - 1) * size(A, 1);
end
3 件のコメント
Beginner
2016 年 5 月 7 日
Image Analyst
2016 年 5 月 7 日
You have to basically do what Jan says twice. Once to find the overall min value, then again to find out all the places it occurs.
You can do it all in one loop if you're clever about it, like resetting the "indexesOfMins" variable that you need to build up each time you encounter a new minimum. You'd also need to concatenate new indexes to that if you ever encounter another value that has exactly the same value as the current min value. See if you can figure it out. If not, the easy no-brainer way is to just do the loop twice, the second time looking for the overall min that you found in the first loop.
Jan
2016 年 5 月 7 日
@Beginner and Image Analyst: My code replies the indices of all values already, which equal the minimum:
a = [3, 3, 4, 4; ...
4, 1, 2, 2; ...
2, 1, 3, 3; ...
3, 2, 1, 3];
[value, pos] = minimum(a)
% value: 1
% pos: 6, 7, 12
カテゴリ
ヘルプ センター および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!