フィルターのクリア

CALCULATION OF MAXIMUM VALUE IN EVERY ROW

2 ビュー (過去 30 日間)
raj
raj 2012 年 3 月 6 日
コメント済み: Stephen23 2016 年 1 月 16 日
suppose there is a matrix of 3x3 size i want to calculate the maximum value in every row.
ex: 3 4 5
6 9 0
1 2 3
the result i should get at the end should be like this
0 0 1
0 1 0
0 0 1
[EDITED, code formatted, Jan]
  2 件のコメント
Brahima DRABO
Brahima DRABO 2016 年 1 月 16 日
suppose your matrix is A: result = A==max(A,[],2)
Stephen23
Stephen23 2016 年 1 月 16 日
@Brahima DRABO: you should put this as an answer too: you would get votes.
Note to others: ignore the accepted answer, it is very poor code.

サインインしてコメントする。

採用された回答

Bart
Bart 2012 年 3 月 6 日
try this:
suppose the input matrix is A, the output result matrix is B;
max = 0;
k = 0;
l = 0;
for i=1:3
for j=1:5
place(i,j) = 0;
end
end
for i=1:3
for j=1:3
if A(i,j)>=max
max = A(i,j);
place(i,j) = 1
end
end
end
for k=1:3
for l=1:3
if place(k,l) = 1
if place(k,l+1) = 1
B(k,l) = 0;
end
if place[k,l+2) = 1
B(k,l) = 0;
else B(k,l) = 1;
end
else B(k,l) = 0;
end
end
end
  1 件のコメント
Jan
Jan 2012 年 3 月 7 日
Shadowing the built-in function "max" by a variable is a frequent source of porblems and bugs.
The creation of the variable "place" element by element is very inefficient and should be avoided. "place = zeros(3, 5);" is nicer, faster and consumes less memory. Although this is a tiny example here and runtime does not matter, it is a good idea to follow a clean programming style.
Using nested loops to create B element by element is slow also, again due to the missing pre-allocation.
It is not useful to declare k=0 and l=0 at the beginning.
The algorithm wastes a lot of time. Try it with a 1000x1000 array to feel the difference.

サインインしてコメントする。

その他の回答 (3 件)

Jonathan Sullivan
Jonathan Sullivan 2012 年 3 月 7 日
m = [ 3 4 5
6 9 0
1 2 3];
mx = max(m,[],2); % EDIT: was max(m,2); Oops
out = bsxfun(@eq,m,mx);
  1 件のコメント
raj
raj 2012 年 3 月 7 日
thanx mate!!!

サインインしてコメントする。


Jan
Jan 2012 年 3 月 6 日
[v, sub] = max(a, [], 2); % [EDITED], was "max(a, 2)"
sa = size(a);
b = zeros(sa);
index = sub2ind(sa, 1:sa(1), sub);
b(index) = 1;
I cannot try it currently and I find the documentation of sub2ind confusing in this point: Perhaps the 2nd and 3rd argument must be swapped: sub2ind(sa, sub, 1:sa(1)).
  2 件のコメント
raj
raj 2012 年 3 月 7 日
there is an error in your code... in the 1st line
Jan
Jan 2012 年 3 月 7 日
Thanks, raj, fixed.

サインインしてコメントする。


raj
raj 2012 年 3 月 7 日
even the imregionalmax function works well

カテゴリ

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