Lagrangian interpolation index exceeds matrix dimensions

1 view (last 30 days)
fid = fopen('force.m','r');
n = fscanf(fid,'%f',1);
a = fscanf(fid,'%f',[2 n]);
x = a(1,:); x = x';
fx = a(2,:); fx = fx';
fclose(fid);
xx = input('\nEnter x value to find f(x): ');
yy = 0.;
for i = 1:n
al = 1.;
for j = 1:n
if j ~= i
al = al*(xx-x(j))/(x(i)-x(j));
end
end
yy = yy + al*fx(i);
end
fprintf('\nValue of f(x) at x = %8.6f', xx)
fprintf('is %14.6e\n' , yy)
When I run my code, the command window keep telling me that
>> interpolation
Index exceeds matrix dimensions.
Error in interpolation (line 4)
x = a(1,:); x = x';
and I don't know how to fix this

Answers (1)

Walter Roberson
Walter Roberson on 19 Oct 2020
>> fid = fopen('force.m','r');
n = fscanf(fid,'%f',1)
n =
[]
>> type force.m
F = [0.107 100;0.172 200;0.238 300;0.351 400;0.388 500;0.417 600;0.432 700;0.441 800]
Your code is expecting force.m to contain a number that defines the number of rows that follow.
a = fscanf(fid,'%f',[2 n]);
and then it is expecting 2 columns (not 2 rows) with the number of rows of data given by the first number in the file.
The code is not expecting something in the form of a MATLAB assignment statement, and is totally unprepared to deal with the variable name, the equal sign, the [ and ], and the semi-colons.
Example of format that would be expected:
8
0.107 100
0.172 200
0.238 300
0.351 400
0.388 500
0.417 600
0.432 700
0.441 800
You need to either change the format of the file, or else you need to change how you read the file.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!