Merge selected column elements from two matrices into a new matrix

5 views (last 30 days)
I have two identically sized matrices. Once matrix, cA, contains the concentration of hydrogen ion while cB contains the concentrations of hydroxide ion. In a specified row, both matrices will have some zero values. For a specific row number, I would like to take the non-zero values of cA and input them into the cA column numbers (which are non zero) in a 3rd matrix, cT. I would also like to take the non-zero values of cB and input them into the cB column numbers (which are non zero) of the identically numbered row for cT. So in row 17 of cA and cB, cA contains non-zero values in columns 1 through 104 whereas cB contains non-zero values in columns 105 through 201. There is never overlap, which means that the row in the new matrix, cT, should not contain any zero values. Also, when the element or cell value for cA is input into cT, I would like to tranform it from hydrogen ion to hydroxide ion using the dissociation constant of water. So the value from cA would be input into cT as follows:
cT(i,j) = 1E-14/cA(i,j)
So, I guess, for a specific row number i, concatenate non-zero values from cA with non-zero values for CB and input that "concatenation" into row i of cT while transforming the cA values as I've outlined above.

Accepted Answer

David Hill
David Hill on 3 Jan 2022
If the number of non-zeros is not constant in the combined cA,cB rows, then cT will need to be a cell array.
for k=1:size(cA,1)
A=cA(k,:);
B=cB(k,:);
cT{k}=[A(A~=0),B(B~=0)];
end
otherwise, if the non-zeros is constant, then a new matrix can be formed
for k=1:size(cA,1)
A=cA(k,:);
B=cB(k,:);
cT(k,:)=[A(A~=0),B(B~=0)];
end
  1 Comment
Robert Demyanovich
Robert Demyanovich on 3 Jan 2022
Not sure I understand. I'm combining non-zero values from columns in cA with non-zero values from columns in cB into the same numbered row of cT. I'm doing a simulation and it has a loop. I'm not sure why you have the "for" statement.
Also the size of all matrices (cA, cB, cT) are exactly the same and are defined at the beginning of the code. The number of columns with non-zero values for a particular row will vary in cA and cB. The concatenated matrix, cT, will never have zero values in a row that has values that came from the concatenation of cA and cB.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!