0

I have two arrays in matlab

a = [1 1.1 1.2 1.1 1.3] 
b = [-2 0 1 2 -4]

For the negative values in array b, example -2 -4, I would like to convert array a into negative, -1 and -1.3.

I have used a 'for' loop, which takes too long for 700 000 columns(possibly hours) looking for a quicker ways to accomplish this. Thanks

2 Answers 2

2

a .* sign(b) works if b has no zero elements, a can have arbitrary elements.

Explanation:

multiply a itemwise with the sign of b.

Null fix:

To fix the null error you can write a function yourself like this (pseudocode):

function r = test_sign(b)
if b==0
   r = 1;
else
   r = sign(b);
end
Sign up to request clarification or add additional context in comments.

1 Comment

thank you guys for helping me with the solution, i have managed to accomplish what i wanted, in micro-fraction'th' time(that before). really appreciate it.
1

You can use logical indexing.

(First I assume a and b have the same length or your question doesn't make sense).

To get a vector that is TRUE when b is negative and FALSE otherwise, you can just do:

b < 0 % depending on what you want, b <= 0

You can use this as an index into a to grab out those corresponding elements:

a( b < 0 )

Now that you've selected the right elements make them negative and assign them back:

a ( b < 0 ) = - a ( b < 0 );

In terms of efficiency, you may want to store the vector b < 0 to avoid re-calculating it (you'll have to try and see which on you prefer):

idx = b < 0;
a(idx) = -a(idx);

Matlab is a vectorised language so most times there is a for loop, you can avoid it. Read up about this sort of matrix indexing here.

2 Comments

thank you guys for helping me with the solution, i have managed to accomplish what i wanted, in micro-fraction'th' time(that before). really appreciate it.
Then please accept the answer you used (click the tick on the top-left).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.