Matlab code for creating matrix
I have a problem, I am working with numerical approximations.
Now I have $-1=x_0<x_1 <...<x_n=1$ with $x_i=x_{i-1}+h$ and $h=2/n$. Now given a function $f$, I want to find $f(x_i)$ for $i=1:n-1$ and store it in a column matrix $F$.
How will I code it in matlab? Here is my code but it does not working. Any help is appreciated.
function F = matrix(f , n) h=2/n; for i=1:n-1; x(0)=-1; x(n)=1 x(i)=h+x(i-1) end
endfunction $\endgroup$ 2 4 Answers
$\begingroup$The function header specifies the output as F, but you don't assign any value to F in your code. Nor do you ever use f. All you are doing is producing the array x (and that in an inefficient way, but that's beside the point).
$\endgroup$ 1 $\begingroup$You could try
function F = f_matrix (f, n) x = transpose(linspace(-1, 1, n+1)); F = f(x);
endfunction $\endgroup$ $\begingroup$ In the version of Matlab that I use, the index starts at 1, instead of 0. So
x(1) = -1;
x(n+1) = 1;
and so on.
Another way to set up the matrix is
x = -1:(2/n):1;
$\endgroup$ $\begingroup$try this which returns not only F but also the x values
function [F,x] = Fmatrix(f, n) h = 2/n; x = zeros(n+1,1); %initialize array with size n+1 F = zeros(n+1,1); for i=1:n+1 x(i) = -1 + h*( i-1 ); F(i) = f(x(i)); end % vector 'x' contains '[x_0,x_1,x_2,..x_n]` % vector 'F' contains '[f(x_0),f(x_1),.. f(x_n)]`
end $\endgroup$ 1