2

im working on octave not sure if it would run in matlab, im trying to do a simple lagrange polynomial that plot the points, the function and the lagrange aproximation, so i did the following,

clear all
clc

function [y] = lagrange(x, x0, y0)

   n = size(x0,1);
   y = 0;

    for i=1:n
        p = 1;
        for j=1:n

            if j == i   % avoiding division by 0
                continue;
            endif;

            p *= (x-x0(j)) / (x0(i)-x0(j));

        endfor;

        y += y0(i) * p;
    endfor;
endfunction;

x=[0:0.1:5];

x0=[2;2.75;4];
y0=[1/2;1/2.75;1/4];

y=lagrange(x,x0,y0);

I'm having the following problem, "operator *: nonconformant arguments (op1 is 1x41, op2 is 1x41)" which only appears when using a vector in x, if i try and evaluate for example lagrange(3,x0,y0) in a specific point, the function works correctly and there is no problem with it, the problem is when you use a larger vector for x,

So my question is, is there a way i can modify the function so it will work with a larger vector x, or there is a way i can plot the function without using the larger vector directly in the function?

Nick J
  • 1,310
  • 12
  • 25
Zigisfredo
  • 123
  • 3
  • it would help if you could tell us what line the error occurs on. I believe the error message should tell you. my guess is it occurs at the 'p*=' line. for the nonconformant argument to have a problem with two things being the same size, it would have to be a matrix multiply, which wants m by n x n by p . – Nick J Mar 22 '17 at 20:37
  • oh, yes i'm sorry for that, and yes, the error was in the 'p*=' line – Zigisfredo Mar 23 '17 at 10:33

1 Answers1

2

The line

p *= (x-x0(j)) / (x0(i)-x0(j));

means

p = p * (x-x0(j)) / (x0(i)-x0(j));

This * means matrix multiplication, and one can't multiply two matrices (1, 41) and (1, 41): inner dimensions do not match.

What you need there is elementwise multiplication,

p = p .* (x-x0(j)) / (x0(i)-x0(j));

(See docs for an explanation of the difference).

It could be written as

p .*= (x-x0(j)) / (x0(i)-x0(j));

But I suggest avoiding such contraction; in Matlab/Octave it's not used as much as in some other languages, possibly because placing two operands side by side makes the errors in binary operation choice more apparent.

  • Interesting. as far as I can tell the elementwise assignment operators are undocumented in octave. At least I didn't see that on the operator doc page, but a quick test shows it does work as you described. And I'm fairly certain Matlab doesn't supports those arithmetic/assignment operators at all. – Nick J Mar 23 '17 at 13:19