How to code sparse diagonal matrix of increasing dimensions

1 view (last 30 days)
I need to code a growing matrix via for loop and evaluate the time fo some computations, but when i plot the time implied related to the computation it doesn't respect the intervals in which i want to calculate it. Please help!
I'd be very grateful!
clc
clear all
close all
for n= 500:50:1000
e = ones(n,1);
A = spdiags([-2*e 0*e 6*e 0*e -2*e],-2:2,n,n);
for i = 1:n
bi(i) = -(i+1)^2;
b = bi';
end
tic;
L1 = chol(A,'lower');
y1 = L1\b;
x1 = L1'\y1;
toc;
t1(n) = toc;
A2 = full(A);
tic;
L2 = chol(A2,'lower');
y2 = L2\b;
x2 = L2'\y2;
toc;
t2(n) = toc;
end
abs_plot = linspace(500,1000,1000);
plot(abs_plot,t1,'ro','markerfacecolor','r')
hold on
plot(abs_plot,t2,'bo','markerfacecolor','b')
axis tight
  1 Comment
Jan
Jan on 16 Jan 2021
I do not understand this sentene: " it doesn't respect the intervals in which i want to calculate it"

Sign in to comment.

Answers (1)

Jan
Jan on 16 Jan 2021
Edited: Jan on 16 Jan 2021
Maybe this is not, what you want:
for n = 500:50:1000
tic
t1(n) = toc;
end
Setting t(500) in the 1st step ist not useful. Better:
nList = 500:50:1000
for k = 1:numel(nList)
n = nList(k);
tic
...
t1(k) = toc; % Not t(n)
end
Or the full code without the time wasting "brute clearing header":
function YourFcn % Smarter than "clear all"
nList = 500:50:1000;
for k = 1:numel(nList)
n = nList(k);
e = ones(n,1);
A = spdiags([-2*e 0*e 6*e 0*e -2*e],-2:2,n,n);
b = -(2:n+1).' .^ 2; % Vectorized instead of a for loop
tic;
L1 = chol(A,'lower');
y1 = L1 \ b;
x1 = L1' \ y1;
t1(k) = toc;
A2 = full(A);
tic;
L2 = chol(A2,'lower');
y2 = L2 \ b;
x2 = L2' \ y2;
t2(k) = toc;
end
plot(nList, t1, 'ro', 'markerfacecolor', 'r')
hold on
plot(nList, t2, 'bo', 'markerfacecolor', 'b')
axis tight
end

Categories

Find more on Loops and Conditional Statements 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!