필터 지우기
필터 지우기

Create a new matrix with 0,-1 and 1 if and where in another matrix appears a max value

조회 수: 2 (최근 30일)
Hello, I try to well explain my problem... I have an array A(200x14) in which all the rows show 14 values for each observation period. I need to create another matrix B in which, for each row, the values need to be 1 if it is the maximum value, -1 if it is the min and 0 otherwise. I try to explain better, for example, if in A, in the first row, the values are: [0.5 1 3 4.6 2.8 3.4 6.7 0.01 2.3 8.4 5.1 7.3 1.8 4.3] in matrix B the values should be [0 0 0 0 0 0 0 -1 0 1 0 0 0 0] and I have to make this for each row (considering that the values in the A rows are not the same for each row). Is it possible?Can someone explain me how? I have tried with if,elseif else...but I think there is something that does not work. THANKS

채택된 답변

Image Analyst
Image Analyst 2016년 5월 7일
Sounds like homework, but hopefully it isn't and then you can use this. It's longer than Roger's and it's a "for loop" approach, but thought you might like to see several different approaches. You forgot to share your ifelse approach though.
m = rand(200, 14); % Create sample data.
B = zeros(size(m)); % Initialize output to all 0's.
for row = 1 : size(m, 1)
% Find max location in this row.
[~, indexOfMax] = max(m(row, :));
% Set B = 1 there
B(row, indexOfMax) = 1;
% Find min location in this row.
[~, indexOfMin] = min(m(row, :));
% Set B = -1 there
B(row, indexOfMin) = -1;
end
  댓글 수: 2
Roger Stafford
Roger Stafford 2016년 5월 7일
편집: Roger Stafford 2016년 5월 7일
There is the difficulty with this approach that if there are multiple maxima (or minima) of the same value within a single row of A, only the first occurrences of these will be recorded in that row of B.
Image Analyst
Image Analyst 2016년 5월 7일
Yes, you're right. In that case use find(m(row, :) == theMax to find all the locations.

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

추가 답변 (1개)

Roger Stafford
Roger Stafford 2016년 5월 7일
편집: Roger Stafford 2016년 5월 7일
B = bsxfun(@eq,A,max(A,[],2))-bsxfun(@eq,A,min(A,[],2));
Note: I am taking you literally in regard to the equalities you require. However when you deal with floating point numbers which result from the decimal fractions you describe, exact equality among them becomes a precarious concept.

카테고리

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