Why the matlab editor (Code Analyser) is not warning about changing size by a variable within a loop
Mostrar comentarios más antiguos
In the 2nd example of the following for-loop the variable A definitely changes its size as it does in the 1st example. However, in one case the editor throws a warning message and in the second case it does not. Why?
A = [];
N = 100;
% 1st example
for k = 1:N
M = 10;
for n = M:-1:1
B(n) = n;
end
A = [A,B]; % Warning: Variable appears to change size on every loop iteration
end
% 2nd example
for k = 1:N
M = 10;
for n = M:-1:1
B(n) = n;
end
A(end+1:end+length(B)) = B; % No warning here and faster
end
If I write in simpler way
A = 1; % or A=[];
for k = 1:N
A(end+1:end+2) = [1,1]; % No warning.
end
And, by the way
A = 1; % or A = [];
for k = 1:N
A = [A,[]]; % Warning: Variable 'A' appears to change size on every loop iteration. Consider preallocating for speed
end
That means Code Analyser is not analysing much here
3 comentarios
I was curious about your remark about the speed, so here is the test. I don't immediately see the reason for this difference, so I made a third option as well.
timeit(@fun1);timeit(@fun2);timeit(@fun3);% warm up online run tool
timeit(@fun1),timeit(@fun2),timeit(@fun3) % actual timing runs
isequal(fun1,fun2)&&isequal(fun1,fun3) % sanity check
function A=fun1
A = [];
N = 100;
for k = 1:N
M = 10;
for n = M:-1:1
B(n) = n;
end
A = [A,B]; % Warning: Variable appears to change size on every loop iteration
end
end
function A=fun2
A = [];
N = 100;
for k = 1:N
M = 10;
for n = M:-1:1
B(n) = n;
end
A(end+1:end+length(B)) = B; % No warning here and faster
end
end
function A=fun3
A = [];
N = 100;
for k = 1:N
M = 10;
for n = M:-1:1
B(n) = n;
end
A(end+(1:numel(B))) = B;
end
end
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!