Simple FOR loop question

I have a column vector (GUI_NEWABS) which contains all positive numbers. I need to change some of the values within it to negative (i.e. *-1) based on whether the associated value in another coloumn vector (GUI_DATA) is positive or negative (GUI_NEWABS is a result of transformations performed on GUI_DATA). Basically I want the sign of the number in each row of GUI_NEWABS to match the sign of the number in the same row of GUI_DATA.
I've tried to use an IF function (i.e. if (sign(GUI_DATA) == 1) but this doesn't work, presumably because the IF function is trying to calculate whether the entire column = 1. Therefore I presumably I need to use a FOR loop to scroll through each value in GUI_DATA. I've tried a couple of different syntax, including the following..
for GUI_DATA
GUI_NEWABS = GUI_NEWABS *(sign(GUI_DATA));
end
however I keep getting an error on the 'for GUI_DATA' line saying that the statement is incomplete/incorrect. Given that I want to scroll through ALL rows of this vector what do I need to put in this line to get it to work?
Thanks Rob

 Risposta accettata

Andrei Bobrov
Andrei Bobrov il 11 Mag 2011
so?
GUI_NEWABS = abs(GUI_NEWABS).*sign(GUI_DATA);

1 Commento

RoJo
RoJo il 11 Mag 2011
BTW, you get the error message because your for loop syntax is not correct.
It should be the below.
But go with the vectorized answer above and you don't need loops.
for i=1:size(GUI_DATA, 1)
GUI_NEWABS(i) = GUI_NEWABS(i)*sign(GUI_DATA(i));
end

Accedi per commentare.

Più risposte (1)

Rob H
Rob H il 11 Mag 2011

0 voti

Hi, adding the 'i''s in was what I was needing thanks, although it has to be GUI_NEWABS(i,:) to get it to return a column vector.
Thanks Rob

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by