The variable ... appears to change size on every loop iteration. Consider preallocating.

6 views (last 30 days)
I've searched and found a lot of answers on this warning but i cant seem to solve it anyway.
Code works to confirm if a word is a palindrome, but i would like to fix the warning.
word='aibohphobia';
L=length(word);
word2=char(1,L)
for n=1:L
word2(n)=word(L-n+1);
end
strcmp(word,word2)
(warning at word2)
I get that it has to change the array size for every loop iteration and if I'm correct I'm supposed to preallocate it beforehand.
I tried doing this by defining word2 before the for loop with:
word2=zeros(1,L)
word2=strings(1,L)
word2=char(1,L)
but then I just get an array with 0's as output.
Thanks in advance.

Accepted Answer

Walter Roberson
Walter Roberson on 26 Feb 2021
word2 = char(zeros(1,L));

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!