MATLAB Answers

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

10 views (last 30 days)
Gnumas
Gnumas on 26 Feb 2021
Commented: Gnumas on 26 Feb 2021
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.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by