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

1 次查看(过去 30 天)
--- 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 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by