How do I change a whole row/column to zero in a matrix relating to a 'greater than' condition.

52 visualizaciones (últimos 30 días)
I have a random network and I would like to make the rows which have the largest sum equal to zero.
A=createsrandomnetwork(100,5)
U=sum(A)
Say the 1st and 50th number in U are the largest, I would want to make that number row and column equal to zero. I know that I could do it by noting down these numbers and then doing this:
A(1,:)=0
A(50,:)=0
A(:,1)=0
A(:,50)=0
But is there an easier, more automatic way where I could say if a value in U is greater than 5 then change the corresponding column/row to zero?

Respuesta aceptada

Guillaume
Guillaume el 8 de Nov. de 2016
To set the rows/columns where the maximum sum is found:
maxsum = max(U); %I'm assuming that U is a vector here
A(U == maxsum, :) = 0;
A(:, U == maxsum) = 0;
To set rows/columns where U is greater than a value
A(U > 5, :) = 0;
A(:, U > 5) = 0;
  2 comentarios
KJones
KJones el 12 de Nov. de 2016
Thank you, this was very helpful. I was also wondering if I wanted to make the 4 highest U value rows go to zero, how would I go about doing that?
Guillaume
Guillaume el 12 de Nov. de 2016
sort the U vector, the first four values of the 2nd output of sort are the indices of the rows you want to zero:
[~, idx] = sort(U, 'descend');
A(idx(1:4), :) = 0;

Iniciar sesión para comentar.

Más respuestas (1)

Alexandra Harkai
Alexandra Harkai el 8 de Nov. de 2016
> But is there an easier, more automatic way where I could say if a value in U is greater than 5 then change the corresponding column/row to zero?
Using logical indexing, you can use 'U>5' to indicate which rows/columns you want to change:
U = sum(A, 2); % sum of rows
disp(U > 5); % display 0-1 values where condition of false/true
A(:, U>5) = 0; % columns
A(U>5, :) = 0; % rows

Categorías

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

Etiquetas

Aún no se han introducido etiquetas.

Community Treasure Hunt

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

Start Hunting!

Translated by