how to create a matrix from another one, using for loop

조회 수: 1 (최근 30일)
Kathrin Chari
Kathrin Chari 2019년 12월 16일
답변: Star Strider 2019년 12월 16일
--- I can't find what really causes the error in this function---
function Ant_Simpl_Mat = r_dnaOnMatrix(mat)
[x,y] = size(mat);
Ant_Simpl_Mat = reshape(blanks(x*y),x,y);
for i=1:x
for j=1:y
if mat(i,j)=='A'
Ant_Simpl_Mat(i,j)='T';
elseif mat(i,j)=='C'
Ant_Simpl_Mat(i,j)='G';
elseif mat(i,j)=='T'
Ant_Simpl_Mat(i,j)='A';
elseif mat(i,j)=='G'
Ant_Simpl_Mat(i,j)='C';
end
end
end
disp(Ant_Simpl_Mat)
end

답변 (1개)

Star Strider
Star Strider 2019년 12월 16일
I do not get an error when I run it.
A simpler approach (that avoids the nested loops and the if block):
Ai = mat == 'A'; % Logical Index
Ci = mat == 'C'; % Logical Index
Ti = mat == 'T'; % Logical Index
Gi = mat == 'G'; % Logical Index
Ant_Simpl_Mat = zeros(size(mat)); % Preallocate Output Matrix
Ant_Simpl_Mat(Ai) = 'T'; % Substitute
Ant_Simpl_Mat(Ci) = 'G'; % Substitute
Ant_Simpl_Mat(Ti) = 'A'; % Substitute
Ant_Simpl_Mat(Gi) = 'C'; % Substitute
Ant_Simpl_Mat = char(Ant_Simpl_Mat) % Convert To ‘char’
It produces the same result as your code with my test matrix, so I assume both are correct.

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by