필터 지우기
필터 지우기

How to replace zeros in one matrix with another matrix

조회 수: 4 (최근 30일)
J
J 2016년 12월 19일
댓글: Guillaume 2016년 12월 19일
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
  댓글 수: 3
Geoff Hayes
Geoff Hayes 2016년 12월 19일
J's answer moved here
Matrix B=[1 0 0 0 0;2 3 0 0 0;4 5 6 0 0;7 8 9 10 0;11 12 13 14 15] You can see that "triu" of matrix B is made of zeros. I need to replace zeros in matrix B using IF statement with matrix A=[1 2 3 4 5;6 7 8 9 10]. Orientation is set and number of zeros is matching matrix A.
Guillaume
Guillaume 2016년 12월 19일
The first option in my answer matches this scenario. if is not needed.

댓글을 달려면 로그인하십시오.

답변 (3개)

Andrei Bobrov
Andrei Bobrov 2016년 12월 19일
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);

Guillaume
Guillaume 2016년 12월 19일
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.

arwa
arwa 2016년 12월 19일
x = [0 0 0 0 0 0 0 0 0 0]; z = [1 2 3 4 5 6 7 8 9 10]; for i=1:1:10 x(1:i)=z(1:i); end
then you can get x = [1 2 3 4 5 6 7 8 9 10] like z instead of zeros..
Do you mean this??

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by