Matlab functions not working properly

I am trying to make such a function in matlab enter image description here

It should be an array of l_k wheres k from 1 to n , but however.

In the code: x - some vector (array), z - scalar; in the code w is the upper part of the hydraulic fracturing and g below.

 function out_l = l_k(z, x) %  l_k   z %x -   %z -       n = size(x); w = 1; g = 1; out_l = zeros(n); for k = 1:n for j = 1:n % w for i=1:n if((i ~= k) && (i ~= j)) w = w * (z - x(i)); end end % g for i=1:n if(i ~= k) g = g * (x(k) - x(i)); end end end out_l(k) = (w/g); end end 

The problem is when it comes to this for loops, it just exits after the first time the if! What happened?

  % w for i=1:n if((i ~= k) && (i ~= j)) w = w * (z - x(i)); end end % g for i=1:n if(i ~= k) g = g * (x(k) - x(i)); end end 
+4
source share
2 answers

String n = size(x); it doesn’t make sense if you want the number of elements in n ( size returns the dimension row vector, not the scalar). Instead, try n=numel(x); .

Later editing: I also see that you highlight the output as follows: out_l = zeros(n); , but you should know that it creates an nxn matrix, not an array, as you might expect. Try out_l = zeros(1,n); for change.

And one more tip: if in doubt, use the F1 key as often as possible. :-) The Matlab Integrated Help explains Matlab very well.

+1
source

Matlab has built-in functions for performing interpolation, such as interp1 ; (I can recognize the Lagrange interpolation functions in your formula).

If you want your own code to evaluate the Lagrange interpolation functions, you should consider using vectors and avoiding loops to speed up your code.

Consider the following:

 x_n = 0:.3:1; % # interpolation nodes k = 3; % # we want for instance the function which is equal to 1 at 3rd node z = .5; % # we want to evaluate the interpolant at z=.5 x_n_l = x_n; x_n_l(k) = []; % # we need all the nodes but the k-th l_k = prod( z - x_n_l )/prod( x_n(k) - x_n_l ) % # this is your value 

Of course, you can wrap the code in a nice feature.

+1
source

All Articles