How do I take my generated string outputs from for loop and return a list?

seq = 'ACAUUUGCUUCUGACACAACUGUGUUCACUAGCAACCUCAAACAGACA'
for i=1:3:numel(seq)-2
a = (seq(i:i+2))
end
a = 'ACA'
a = 'UUU'
a = 'GCU'
a = 'GAC'
etc...
% Desired output --> ['ACA', 'UUU', 'GCU', 'GAC' ...]

 Accepted Answer

You should be careful what you ask for. 'ACA' is the 1 x 3 char vector ['A' 'C' 'A'] and ['ACA' 'UUU'] is concatenating two 1 x 3 vectors together getting a 1 x 6 vector 'ACAUUU' -- back to where you started
seq = 'ACAUUUGCUUCUGACACAACUGUGUUCACUAGCAACCUCAAACAGACA'
seq = 'ACAUUUGCUUCUGACACAACUGUGUUCACUAGCAACCUCAAACAGACA'
a1 = [];
a2 = cell(0);
for i=1:3:numel(seq)-2
a1 = [a1, seq(i:i+2)];
a2{end+1} = seq(i:i+2);
end
a1
a1 = 'ACAUUUGCUUCUGACACAACUGUGUUCACUAGCAACCUCAAACAGACA'
a2
a2 = 1×16 cell array
{'ACA'} {'UUU'} {'GCU'} {'UCU'} {'GAC'} {'ACA'} {'ACU'} {'GUG'} {'UUC'} {'ACU'} {'AGC'} {'AAC'} {'CUC'} {'AAA'} {'CAG'} {'ACA'}
a3 = reshape(seq, 3, []).'
a3 = 16×3 char array
'ACA' 'UUU' 'GCU' 'UCU' 'GAC' 'ACA' 'ACU' 'GUG' 'UUC' 'ACU' 'AGC' 'AAC' 'CUC' 'AAA' 'CAG' 'ACA'
I would suggest to you that the a3 method is easiest. You might want to cellstr() or string() the resutling 16x3 array.

More Answers (1)

Here si the solution:
a=[];
seq = 'ACAUUUGCUUCUGACACAACUGUGUUCACUAGCAACCUCAAACAGACA'
seq = 'ACAUUUGCUUCUGACACAACUGUGUUCACUAGCAACCUCAAACAGACA'
for i=1:3:numel(seq)-2
a = [a; (seq(i:i+2))];
end
a
a = 16×3 char array
'ACA' 'UUU' 'GCU' 'UCU' 'GAC' 'ACA' 'ACU' 'GUG' 'UUC' 'ACU' 'AGC' 'AAC' 'CUC' 'AAA' 'CAG' 'ACA'

1 Comment

It is inefficient to keep expanding an array in a loop like that.
Simpler and much more efficient:
seq = 'ACAUUUGCUUCUGACACAACUGUGUUCACUAGCAACCUCAAACAGACA';
mat = reshape(seq,3,[]).'
mat = 16×3 char array
'ACA' 'UUU' 'GCU' 'UCU' 'GAC' 'ACA' 'ACU' 'GUG' 'UUC' 'ACU' 'AGC' 'AAC' 'CUC' 'AAA' 'CAG' 'ACA'

Sign in to comment.

Products

Release

R2022b

Community Treasure Hunt

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

Start Hunting!