Borrar filtros
Borrar filtros

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

2 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Image Analyst
Image Analyst el 7 de Mayo de 2016
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 comentarios
Roger Stafford
Roger Stafford el 7 de Mayo de 2016
Editada: Roger Stafford el 7 de Mayo de 2016
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 el 7 de Mayo de 2016
Yes, you're right. In that case use find(m(row, :) == theMax to find all the locations.

Iniciar sesión para comentar.

Más respuestas (1)

Roger Stafford
Roger Stafford el 7 de Mayo de 2016
Editada: Roger Stafford el 7 de Mayo de 2016
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.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by