0

If you have a random matrix, for example a 5x5:

A(i,j) = (5 4 3 2 1
          4 3 2 1 0
          5 4 3 2 1
          4 3 2 1 0
          5 4 3 2 1)

And a second array:

B(1,j) = (4 5 6 7 8)

How can I then assign values of B to A if this only needs to be done when the value of B(1,j) is larger than any of the values from a certain colomn of A?

For example, B(1,1) = 4 and in the first colomn of A it is larger than A(1,1), A(3,1) and A(5,1), so these must be replaced by 4. In the second colomn, nothing needs to be replaced, etc.

Thanks already!

2 Answers 2

5

You can do this without any explicit looping using bsxfun:

A = [5 4 3 2 1
     4 3 2 1 0
     5 4 3 2 1
     4 3 2 1 0
     5 4 3 2 1];
B = [4 5 6 7 8];

A = bsxfun(@min,A,B);

Result:

A =

   4   4   3   2   1
   4   3   2   1   0
   4   4   3   2   1
   4   3   2   1   0
   4   4   3   2   1

In later versions of MATLAB (2016b and later) you can even omit the bsxfun and get the same result.

A = min(A,B);
Sign up to request clarification or add additional context in comments.

Comments

0

Matlab "find" may be of use to you.

https://www.mathworks.com/help/matlab/matlab_prog/find-array-elements-that-meet-a-condition.html

If you aren't concerned about speed or efficiency, you could also set up a two nested for loops with a condition (i.e. an if) statement comparing the values of A and B.

If you only interested in column wise comparison to B, you could use the increment of the outer loop in the inner loop.

for i,...
 for j,...
   if B(1,i) > A(j,i)
       A(j,i)=B(i,j)

Comments

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.