MATLAB Answers

find negative values of simple summation. code efficiency

1 view (last 30 days)
Ansgar Elles
Ansgar Elles on 3 Jan 2021
Answered: Walter Roberson on 5 Jan 2021
Hello, I have the following statement which must be true: v1_before(1) == v1_transferred_vector(1) + v1_conserved_vector(1)
My goal is to find out which of the two elements on the right side are actually negative. The algebraic sign of "v1_before" is already known, as well as the absolute values of the two elements on the right side.
The indices refer to the x-value of the [x,y] vectors. So i will do exactly the same with (2) / y-values too.
I coded the following. But im wondering whether there is a more elegant and efficient way to do it. Many thanks in advance!!!!
%determine whether + / - for x-values
if v1_before(1) - v1_transferred_vector(1) - v1_conserved_vector(1) == 0 %==0 when difference is smaller then 1e-15/eps
%do nothing, leave them positiv
elseif v1_before(1) + v1_transferred_vector(1)- v1_conserved_vector(1) == 0
v1_transferred_vector(1) = - v1_transferred_vector(1);
elseif v1_before(1) - v1_transferred_vector(1) + v1_conserved_vector(1) == 0
v1_conserved_vector(1) = - v1_conserved_vector(1);
else %v1_before(1) + v1_transferred_vector(1) + v1_conserved_vector(1) == 0
v1_transferred_vector(1) = - v1_transferred_vector(1);
v1_conserved_vector(1) = - v1_conserved_vector(1);
end
  6 Comments

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 5 Jan 2021
M = [1 1; 1 -1; -1 1; -1 -1];
m = M(v1_before(1) == M*[v1_transferred_vector(1); v1_conserved_vector(1)],:);
v1_transfered_vector(1) = m(1)*v1_transfered_vector(1);
v1_conserved_vector(1) = m(2)*v1_conserved_vector(1);
This can be vectorized with a slight bit of work.

Community Treasure Hunt

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

Start Hunting!

Translated by