Merge selected column elements from two matrices into a new matrix

조회 수: 4 (최근 30일)
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.

채택된 답변

David Hill
David Hill 2022년 1월 3일
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
Robert Demyanovich
Robert Demyanovich 2022년 1월 3일
편집: Robert Demyanovich 2022년 1월 3일
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.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Particle & Nuclear Physics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by