MATLAB: Subscript indices must either be real positive integers or logicals error, how can I fix

for loop subscript indices error matrix store

for n = 0:50:500
A = rand(n,n);
tic;
[L, U] = lu_nopivot(A,n);
toc;
endtime = toc;
m(n) = [log(endtime), log(n)]
end
plot(m)
When I run the code above I get the error about subscript indices. This uses a function I've defined which gets the LU decomposition of a matrix A. The aim is to generate a 50×50, 100×100, 150×150, …, 500×500 matrix with random numbers inside, then use the function to learn of the L & U matrix's. This should be timed as I wish to plot the log of the time vs the log of the n used in the nxn matrix for A. What am I doing wrong?
Thank you in advance.
Code used for the function
function [L, U] = lu_nopivot(A,n)
L = eye(n);
for k = 1 : n
L(k + 1 : n, k) = A(k + 1 : n, k) / A(k, k);
for l = k + 1 : n
A(l, :) = A(l, :) - L(l, k) * A(k, :);
end
end
U = A;
end

Best Answer

The error message tells us that you are trying to index using an inappropriate value. Have a look at this line:
m(n) = ...
MATLAB indexing starts at one, not zero, but your first n value is zero. The solution is to iterate over indices not values. Therefore you want to do something like this (untested because I do not have your data or functions):
vec = 0:50:500;
arE = nan(size(vec));
arN = nan(size(vec));
for k = 1:numel(vec)
A = rand(vec(k));
tic;
[L,U] = lu_nopivot(A,vec(k));
toc;
arE(k) = log(toc);
arN(k) = log(vec(k));
end