Column indexing with condition

5 visualizaciones (últimos 30 días)
Duc Anh Le
Duc Anh Le el 27 de Abr. de 2020
Respondida: per isakson el 28 de Abr. de 2020
I have two matrices
A = [1, 0, 0;
0, -2, 0;
0, 0, -3];
B =[1, 2, 3;
4, 5, 6;
7, 8, 9];
I need to find columns in A with negative values (in this example it's 2 and 3 columns) and change the values to opposite in the corresponding columns of B. Basically, I want
B = [1, -2, -3;
4, -5, -6;
7, -8, -9];
Is there a fast way to do this using indexing? I know how to do this with a for loop, but I believe that's not the best solution

Respuesta aceptada

per isakson
per isakson el 28 de Abr. de 2020
Try this
>> isn = any( A<0, 1 );
>> B(:,isn) = -B(:,isn)
B =
1 -2 -3
4 -5 -6
7 -8 -9
and read about Indexing with Logical Values (in the middle of the page)

Más respuestas (0)

Categorías

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

Etiquetas

Productos


Versión

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by