MATLAB: Replace values of one column of matrix size 1*n to another matrix of size n*n

MATLABmatrixmatrix array

I am new in Matlab programming and unable to solve might be simple problem.
I have a question regarding matrix column replacement. I have a matrix A of size example: 1*16 such as
A = [.01 0 0 0 .42 0 0 0 .13 0 0 0 .09 0 0 .32]
and another matrix B of size 16*16 with all values of column the same
B =
[.12 .18 .08 .17 .43 .13 .13 .24 .09 .11 .04 .08 .10 .15 .08 .43]
each row same as first row.
I want to replace columns of B with columns of A but if 0 is present in A I should keep the value of B of that column the same.
I want to get output as 16*16 matrix with a sample row matrix C as:
C = [.01 .18 .08 .17 .42 .13 .13 .24 .13 .11 .04 .08 .09 .15 .08 .32]
I would be pleased to get support. I am unable to find a clue as I said I am new in matlab.
Thank you.

Best Answer

A = [.01 0 0 0 .42 0 0 0 .13 0 0 0 .09 0 0 .32];
B = repmat([.12 .18 .08 .17 .43 .13 .13 .24 .09 .11 .04 .08 .10 .15 .08 .43], 16, 1);
The simplest way to do what you want is to repmat A to have as many rows as B:
A = repmat(A, size(B, 1), 1);
You then want to replace the values of B where A is not 0 with the corresponding values of A where A is not zero. This is simply written as:
B(A ~= 0) = A(A ~= 0)
All done. You could also have written the last line as
B(A ~=0 ) = nonzeros(A)