1. ## algorithms in matlab

Hey guys.

So I've only ever used matlab for simple matrix multiplication, and I've never written a program with inputs and outputs and loops and such. I tried looking for samples online, but I couldn't find anything I was able to understand.

I tried writing the following program:

Code:
function [ y ] = divdif( n,x,y )

for j=1:n
d(j)=y(j)
end
for i=2:n
for j=1: n-i
d(i*n+j)=(d((i-1)*n+(j+1))-d((i-1)*n+j))/(x(j+i)-x(j))
end
y(i)=d(i*n+0)
end
(x and y are supposed to be vectors of length n, hence the input data. Same for d.)

But it's not working. Any suggestions on how to fix it?

Thanks!

2. ## Re: algorithms in matlab

Originally Posted by hatsoff
Hey guys.

So I've only ever used matlab for simple matrix multiplication, and I've never written a program with inputs and outputs and loops and such. I tried looking for samples online, but I couldn't find anything I was able to understand.

I tried writing the following program:

Code:
function [ y ] = divdif( n,x,y )

for j=1:n
d(j)=y(j)
end
for i=2:n
for j=1: n-i
d(i*n+j)=(d((i-1)*n+(j+1))-d((i-1)*n+j))/(x(j+i)-x(j))
end
y(i)=d(i*n+0)
end
(x and y are supposed to be vectors of length n, hence the input data. Same for d.)

But it's not working. Any suggestions on how to fix it?

Thanks!
1. If you want help then report what the error messages associated with this not working are.

2. Tell us what you expect this function to do.

3. Do not use the same variable name for the return object as an argument.

4. Do not pass redundant arguments to the function

5. Do not try to address arrays out of bounds (code in red below).

Code:
function [ rv ] = divdif(x,y )

n1=length(x);
n2=length(y);
if n1 ~= n2
disp("error arguments are non-conformant");
return
end
n=n1;

d=y;

for i=2:n
for j=1: n-i
d(i*n+j)=(d((i-1)*n+(j+1))-d((i-1)*n+j))/(x(j+i)-x(j))
end
rv(i)=d(i*n+0)
end
CB