Matlab for loop output into a vector

2.3k Views Asked by At

this is where im at right now, the only thing i need is to be able to stop the procedure if error is below tolerance.

function [ z ] = dome(x,tol)
format short
n=length(x);
z = zeros(n, 2);
z(:,1) = x;
for i=3:n;
gprime=abs(x(i)-x(i-1))/abs(x(i-1)-x(i-2));
e=(abs(gprime)/(abs(gprime-1)))*abs(x(i)-x(i-1));
if e<tol break 
end
z(i,2)=e;
end 

my output now is ans =

1.0000         0
1.5000         0
1.2870    0.1582
1.4025    0.1371
1.3455    0.0557
1.3752    0.0323
1.3601    0.0155
1.3678    0.0082
1.3639         0
1.3659         0
1.3649         0
1.3654         0
1.3651         0
1.3653         0
1.3652         0
1.3652         0
1.3652         0
1.3652         0

how can i make the program only show the table up to error tolerance level?

2

There are 2 best solutions below

2
On BEST ANSWER

How about this:

b = [0,0,abs(x(3:end) - x(2:end-1))];
out = [x',b'];

Edit: here's a version that uses a for loop.

n = length(x);
b = zeros(n,2);

for i = 3:n

    b(i,2) = abs(x(i) - x(i-1));

end

b(:,1) = x';
2
On

The following should do it


function b = differences(x)

n = length(x); b = zeros(n, 2);
b(:, 1) = x;
b(3:n, 2) = abs(x(3:n) - x(2:n-1));

If you want to use the forloop, you can replace b(3:n, 2) = abs(x(3:n) - x(2:n-1)); by for i = 3:n; b(i, 2) = abs(x(i) - x(i-1));