You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 L variable is initialized as ones(size(x)), which is a 1D array (assuming x is a scalar or 1D vector). But you’re trying to index it with L(1:i-1, i+1:n)—this treats L like a 2D matrix, which it’s not, and when i=1, 1:i-1 becomes an empty range, leading to invalid indexing.
  • Broken base function calculation: The way you’re trying to update L using slice operations doesn’t align with how Lagrange basis functions work. Each L_i(x) needs to be calculated for every element in x by multiplying terms for all j ≠ 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 of L that doesn’t match the size of y, 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

  1. Simplified inner loop: Instead of creating a custom range [1:i-1 i+1:n], we just loop through all j from 1 to n and skip j=i with a clear condition. This avoids messy array concatenation and invalid indexing.
  2. Element-wise operations: Using .* ensures that every element in x gets the correct calculation for the i-th Lagrange basis function. This works whether x is a single scalar or a vector of multiple points.
  3. Correct result accumulation: We multiply the full L array (matching the size of y) by Y(i) and add it to y, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:37:03