File: ef230-2023-08/www/examples/matrix_growth_times.m Download
% comparison of matrix expansion times
clear all; clc; close all
powers=1:.2:7;
for j=1:length(powers)
    clear x1 x2 x3;
    n=round(10.^powers(j));
    disp(['Matrix test for ' num2str(n) ' elements']);
    disp('Growing...');
    tic
    for i=1:n
        x1(i)=i^2;
    end
    gr(j)=toc;
    disp('Preallocating...');
    tic
    x2=zeros(n,1);
    for i=1:n
        x2(i)=i^2;
    end
    pa(j)=toc;
    disp('Without for...');
    tic
    x3=(1:n).^2;
    wf(j)=toc;
end
plot(powers,gr,'r-')
hold on
plot(powers,pa,'b-')
plot(powers,wf,'g-')
legend('Growing','Preallocate','Without For')
xlabel('Matrix size 10^x');
ylabel('Execution time (sec)');
title('Comparison of matrix expansion times');