subtracting a previous vector from the current vector in an iteration

Hello please I am trying to create a command that finds a difference between the current and precious vector in an iteration so that if its less than an error marging my values remain the same. so that the my values will remain the same until it detects a significat change in the parameter. For example: p = [ 1 1 0.5]';marg= 1e-3;
[d,g]= func(x,u,p)
for i = 1:100
err(i+1) = p(i+1)-p(i).
if err <=marg
d(i)= d(i-1) %d and g remains the same as the previous
else
[d,g]= func(x,u,p) % compute a new d and g with respect to the new p values.
end.
I have been trying to do this but it keepe telling me cannot access ...p(:,4) because value p(3,1). Please I hope my uestion is clear enough I urgently need help with this. Thanks

3 Comments

Several issues:
  • new_vec - old_vec is a vector. How do you want to compare it to your (scalar) error margin? (one option: sum the absolute differences). Or, do you want to compare elements of a single vector?
  • you don't actually update p anywhere in this code
  • use code formatting blocks:
p = [ 1 1 0.5]';
marg= 1e-3;
[d,g]= func(x,u,p)
for i = 1:100
err(i+1) = p(i+1)-p(i).
end
if err <=marg
d(i)= d(i-1) %d and g remains the same as the previous
else
[d,g]= func(x,u,p) % compute a new d and g with respect to the new p values.
end
I want to compare the difference between the two vectors, so I guess I will mutiply my error by a vector of the number of the p. I keep getting the error
'Attempted to access p(3); index out of bounds because numel(p)=2.
Error in IHM(line 281)
errp(k+1) = abs(p(k+1) - p(k));'
I don't know how I will do it that is why I am requesting for help. I understand it could be my indexing that is the issue. That is why I present the idea of what I would like to do.
Can you include your current code (in a code block)? The code above should not throw that error.
If you want to ensure every element remains the same within margin, compare the max error to marg rather than expanding marg to a vector

Sign in to comment.

Answers (0)

Asked:

on 28 Jun 2020

Commented:

on 29 Jun 2020

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!