Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matlab: Error/precision when evaluating vector

Tags:

matlab

I noticed what was for me an unpredicted behavior when evaluating vectors. It seems is really different doing it directly than indexing within a loop. Can anyone give me some help with this? i know is probably explained in how it makes each operation, so i need some keys about how to look for it

thanks for advise thanks in advance

example:

x=[0.05:.01:3];
n=size(x,2);
y1 = (8*x-1)/(x)-(exp(x));

for i=1:n
    y2(i)=(8*x(i)-1)/(x(i))-(exp(x(i)));
end

a1=[x;y1];
a2=[x;y2];

plot(x,y1, 'red')
hold on
plot(x,y2, 'blue')

here the plot: http://i.stack.imgur.com/qAHD6.jpg

results:

a2:
0.05   -13.0513
0.06   -9.7285
0.07   -7.3582
0.08   -5.5833
0.09   -4.2053
0.10   -3.1052
0.11   -2.2072
0.12   -1.4608
0.13   -0.8311
0.14   -0.2931
0.15   0.1715
0.16   0.5765




a1:
0.05   6.4497
0.06   6.4391
0.07   6.4284
0.08   6.4177
0.09   6.4068
0.10   6.3958
0.11   6.3847
0.12   6.3734
0.13   6.3621
0.14   6.3507
0.15   6.3391
0.16   6.3274
like image 847
myradio Avatar asked Jan 17 '23 13:01

myradio


2 Answers

What you want is:

 y1 = (8*x-1)./(x)-(exp(x));   % note the ./

instead of:

 y1 = (8*x-1)/(x)-(exp(x)); 

As a side note, you can type help / to see what your original first statement was really doing. It was effectively doing (x'\(8*x-1)')' (note the backslash).

like image 151
Chris A. Avatar answered Feb 01 '23 03:02

Chris A.


The error is in your first vector calculation of y1. The problem is in the part where you divide by x. Vector/Matrix division is different from single element division and will return a vector/matrix result.

The solution is to do element-by-element division of these vectors. The vector notation shortcut for this is to use ./ (dot-divide):

y3 = (8*x-1)./(x)-(exp(x));

Now you should find that y2 and y3 are identical.

like image 40
lubar Avatar answered Feb 01 '23 03:02

lubar