Asked by J
on 19 Dec 2016

Hello, how to replace zeros in one matrix with another matrix using if statement? Dimensions are the same; first matrix has 10 zeros and second matrix has 10 numbers. Thanks for answers J

Answer by Andrei Bobrov
on 19 Dec 2016

A = [1:3, 0,0 7,12,0]';% your first array

B = randi(20,8,1); % your second array

t = A == 0;

A(t) = B(t);

Sign in to comment.

Answer by Guillaume
on 19 Dec 2016

An example would clarify what you want. Possibly:

To replace all zero values in A by consecutive values in B, B must have as many elements as there are zeros in A:

assert(numel(B) == numel(A == 0)); %B must have as many elements as there are zeros in A

A(A == 0) = B %replace zeros values in A by values in B

or to replace zeros values in A by values in B in the same position, B must be the same size as A:

assert(isequal(size(B), size(A)));

A(A == 0) = B(A == 0)

An if is most likely not needed.

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 3 Comments

## Geoff Hayes (view profile)

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/317504-how-to-replace-zeros-in-one-matrix-with-another-matrix#comment_414943

## Geoff Hayes (view profile)

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/317504-how-to-replace-zeros-in-one-matrix-with-another-matrix#comment_414971

## Guillaume (view profile)

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/317504-how-to-replace-zeros-in-one-matrix-with-another-matrix#comment_414976

Sign in to comment.