Indexing Error - can't get for loop to function because indices are incorrect
Show older comments
function basis = regbas(CorrectionType)
basisN0 = @(x)[ 1 ];
basisN1 = @(x)[ 1, x ];
basisN2 = @(x)[ 1, x, x^2 ];
basisN3 = @(x)[ 1, x, x^2, x^3 ];
if strcmp(CorrectionType,'Constant')
basis = basisN0
elseif strcmp(CorrectionType,'Linear')
basis = basisN1
elseif strcmp(CorrectionType,'Quadratic')
basis = basisN2
elseif strcmp(CorrectionType,'Cubic')
basis = basisN3
else
disp("Error - CorrectionType should be either 'Constant', 'Linear', 'Quadratic' or 'Cubic'.")
end
end
This function defines "basis"
function coef = alsqr(arr,basis)
x = arr(:,1); % time is column 1
y = arr(:,2); % change second value for column based on which acceleration data you're using
if length(x) ~= length(y); disp('Error - The dimensions of the x and y value lists in the data are not the same')
end
order = length(basis(1));
n = length(x);
A = ones(n,order);
for ORD = 1:order
vec = basis(ORD);
for dat = 1:n
A(dat, ORD) = vec(x(dat)); % ERROR OCCURS HERE
end
end
AT = A';
AA = AT*A;
Ay = AT*y;
w = AA\Ay;% same as inv(AA)*Ay;
coef = round(w,9);
end
I am looking to create a matrix "A" that has length(x) rows and the same number of columns as basis. When I run this function (alsqr), I get an error inside the second for loop telling me "Array indices must be positive integers or logical values." I have tried many different formats and can't get it to run correctly. These functions are to solve for a least squares regression.
Accepted Answer
More Answers (0)
Categories
Find more on Matrix Indexing 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!