MATLAB: How to fix: Index Exceeds Matrix Dimensions

bioinformatics

I am trying to do this problem and keep coming up with the error when I try to take the average of 10 entropies.
%Generate 10 random DNA sequences with at least 1200 nucleotides and %compute its average entropy.
for i = 1:10 s = randseq(1200);
p1 = length(find(s=='A'))/length(s);
p2 = length(find(s=='C'))/length(s);
p3 = length(find(s=='G'))/length(s);
p4 = length(find(s=='T'))/length(s);
entropy = -(p1*log2(p1)+p2*log2(p2)+p3*log2(p3)+p4*log2(p4));
end
avgentropy = entropy(i)/(i);
fprintf('\n The average entropy of the 10 sequences is:\n'); disp(entropy);
Said Error: Index exceeds matrix dimensions.
Error in quiz4 (line 38) avgentropy = entropy(i)/(i);

Best Answer

You forgot to index entropy inside your loop (and pre-allocation, and you forgot to push the {}Code button after selecting your code).
entropy=zeros(1,10);
for i = 1:numel(entropy)
s = randseq(1200);
p1 = length(find(s=='A'))/length(s);
p2 = length(find(s=='C'))/length(s);
p3 = length(find(s=='G'))/length(s);
p4 = length(find(s=='T'))/length(s);
entropy(i) = -(p1*log2(p1)+p2*log2(p2)+p3*log2(p3)+p4*log2(p4));
end
avgentropy = entropy(end)/numel(entropy);
fprintf('\n The average entropy of the 10 sequences is:\n'); disp(entropy);
Also, you might have meant to use mean and/or disp(avgentropy).