How to multiply -1 with specific vector of a matrix ?

Dear all,
I would like to multiply -1 in all elements of column vector of a matrix in the following conditions: 1) if all elements of the column vectors of the matrix are negative. 2) if some elements of the column vectors are negative and rest of them are positive 3) if all elements of the column vectors are positive, don't need to multiply with -1
would you please give me some idea how can i proceed??? for example the matrix is
A=[-0.5 2 3 -5; -0.8 -7 4 6; -0.9 2 3 -9; -0.3 -6 3 1; -0.2 5 3 -7]
result should be like that Result_A=[0.5 -2 3 5; 0.8 7 4 -6; 0.9 -2 3 9; 0.3 6 3 -1; 0.2 -5 3 7]
Thanks in advance.

 Respuesta aceptada

Sean de Wolski
Sean de Wolski el 29 de En. de 2015
Editada: Sean de Wolski el 29 de En. de 2015
The easiest and likely fastest way to do this would be with a simple for-loop over columns.
C = A;
for ii = 1:size(C,2)
if any(sign(C(:,ii)) == -1)
C(:,ii) = -C(:,ii);
end
end
But just for fun, here's a vectorized way:
A=[-0.5 2 3 -5; -0.5 -2 4 6; -0.5 2 3 -9; -0.5 -2 3 1; -0.5 2 3 -7]
B = bsxfun(@times,A,-((double(any(sign(A)==-1)))-0.5)*2)

3 comentarios

D Bhuiyan
D Bhuiyan el 29 de En. de 2015
Thank you so much for four nice answer. Second method works properly but the first method using for loop doesn't works? why...?
thanks
Closing parenthesis was in the wrong place. Try it now.
And, Sean, this is why you should always assert!
assert(isequal(B,C))
D Bhuiyan
D Bhuiyan el 30 de En. de 2015
Thanks a lot:)

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Preguntada:

el 29 de En. de 2015

Comentada:

el 30 de En. de 2015

Community Treasure Hunt

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

Start Hunting!

Translated by