Problem finding max value of column of an Matrix

조회 수: 2 (최근 30일)
Sayanta
Sayanta 2011년 5월 13일
Dear Experts,
I have some loop problem in matlab, I can't find where is the exact problem in my loop , Could please help me in that :)
A = [ 0 1 2 3 4 25 6 7 8 9 ; 9 5 1 20 3 6 4 7 8 5]'
for i=1:size(A,1) for n=1:size(A,2) if A(i,n) == max(A(:,n)) A(i,n)=1 else A(i,n)=0 end end end
the Correct result I expect from the program like this :
0 0
0 0
0 0
0 1
0 0
1 0
0 0
0 0
0 0
0 0
But I getting the error result like
0 0
0 0
0 0
0 1
0 0
1 0
0 0
0 0
0 1
1 1
Many thanks
Good weekend
With Regards
Sayanta

채택된 답변

Laura Proctor
Laura Proctor 2011년 5월 13일
A = [ 0 1 2 3 4 25 6 7 8 9 ; 9 5 1 20 3 6 4 7 8 5]'
c1 = A(:,1) == max(A(:,1));
c2 = A(:,2) == max(A(:,2));
A = [c1 c2];
You'll end up with a logical array as a result, but it will give the results you want. If it needs to be an array of type double, just cast it to double:
double(A)
If you would like to not create variables c1 and c2, then you can just replace c1 with A(:,1) and c2 with A(:,2) which will result in A as type double.
The problem with your initial code is that you're overwriting values in A in each loop.

추가 답변 (1개)

Andy
Andy 2011년 5월 13일
The problem you're having is that you recalculate the max of each column on each iteration of the loop. You could move that calculation out of the loop, or not use a loop at all:
A = [ 0 1 2 3 4 25 6 7 8 9 ;
9 5 1 20 3 6 4 7 8 5]';
[dummy,mA] = max(A,[],1); % max of each column
B = zeros(size(A));
B(sub2ind(size(A),mA,[1 2]))=1; % enter 1s for each max

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by