Search code examples
arraysmatlab

how to operate on a Matlab vector A with a condition from vector B and a condition from the values of vector A


I have two vectors. One with time information and one with channel information.
For example, A has time values

A = 1, 2.5, 2.7, 3, 4, 5, 6, 7, 8, 9, 10

and B has channel values

B = 1, 1, 2, 2, 2, 1, 2, 1, 2, 1, 1

I wish to add a number to the elements of array A, only when array B == 1 and only when the value of those elements in array A are between 7 and 9 for example (A >=7 & A <=9).

I know how to do it for one constraint, but not for the second one. For one constraint I would use

A(B==1)=A(B==1) + "some number"

I need to do this because the number I add will change depending upon the values in array A. I will eventually need to add numbers to every value in A if it is a channel 1 value. My arrays are moderately large - 10^8 elements, but I only need to use about 50 ranges in array A. The values are monotonically increasing, but not by regular amounts.

If I can do it for one range, I don't mind looping on the other ranges.


Solution

  • You can use the same logic as in the code that you use for one constraint. It is better to define an indexing variable, so you can use it in both sides of the assignment statement:

    ind = (B==1) & (A>=7) & (A<=9); % logical index of elements to be modified
    A(ind) = A(ind) + some_number;