Matlab拉格朗日插值函数报错求助:索引超出矩阵维度
Fixing the 'Index exceeds matrix dimensions' Error in Your Lagrange Interpolation Code
Let’s walk through exactly what’s causing that frustrating index error in your code, and fix it so your Lagrange interpolation works as expected.
First, the Root Causes of the Error
Looking at your code, there are a few key mistakes triggering the index out-of-bounds issue:
- Incorrect 2D indexing on a 1D array: Your
Lvariable is initialized asones(size(x)), which is a 1D array (assumingxis a scalar or 1D vector). But you’re trying to index it withL(1:i-1, i+1:n)—this treatsLlike a 2D matrix, which it’s not, and wheni=1,1:i-1becomes an empty range, leading to invalid indexing. - Broken base function calculation: The way you’re trying to update
Lusing slice operations doesn’t align with how Lagrange basis functions work. EachL_i(x)needs to be calculated for every element inxby multiplying terms for allj ≠ i, not by slicing arrays incorrectly. - Wrong slice when accumulating results: The line
y = y+Y(i)*L(1:i-1)uses an arbitrary slice ofLthat doesn’t match the size ofy, which also contributes to dimension mismatches.
Corrected Code
Here’s the fixed version of your function, with explanations of each change:
function y = lagrange(X, Y, x) n = length(X); if n ~= length(Y) error('X and Y must have the same length.'); end y = zeros(size(x)); % Initialize result array to match x's dimensions for i = 1:n L = ones(size(x)); % Start with all 1s for the i-th basis function % Iterate over all points, skipping the i-th one for j = 1:n if j ~= i % Element-wise multiplication to update L for every x value L = L .* (x - X(j)) / (X(i) - X(j)); end end % Add the weighted basis function to the final result y = y + Y(i) * L; end end
Key Changes Explained
- Simplified inner loop: Instead of creating a custom range
[1:i-1 i+1:n], we just loop through alljfrom 1 tonand skipj=iwith a clear condition. This avoids messy array concatenation and invalid indexing. - Element-wise operations: Using
.*ensures that every element inxgets the correct calculation for thei-thLagrange basis function. This works whetherxis a single scalar or a vector of multiple points. - Correct result accumulation: We multiply the full
Larray (matching the size ofy) byY(i)and add it toy, so there’s no dimension mismatch here.
Test It Out
To verify it works, try this example:
X = [1, 2, 3]; Y = [2, 4, 8]; x = 1.5; disp(lagrange(X, Y, x)); % Should return 3, which is the interpolated value at x=1.5
内容的提问来源于stack exchange,提问作者hylian
相关产品推荐
相关产品推荐

