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
                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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With