find negative values of simple summation. code efficiency

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

I don't think there is an elegant way to do this (your code is already fairly clear and efficient), but you could consider storing the three values in temporary variables and using a nested loop (or ndgrid) to make sure you don't miss any combination and it is still easy to adapt the code.
thank you very much Rik, I appreciate your help!
Matt J
Matt J 2021년 1월 4일
편집: Matt J 2021년 1월 4일
Why is efficiency necessary if you are only doing this for v1_before(i) with i=1?
Im not sure. So its only necessary to think about efficiency if its a repetitive task? e.g. in a loop?
If this code only runs once it doesn't matter if it takes 1 ms or 100 ms, but if this code is executed thousands of times in a time-sensitive context, then it does start to matter.
The main point is to spend time optimizing the code that matters. You can spend a few hours here to save a few miliseconds, or spend your time on code that runs often and takes longer to complete.
ok thanks

댓글을 달려면 로그인하십시오.

답변 (1개)

Walter Roberson
Walter Roberson 2021년 1월 5일
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.

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

릴리스

R2019b

질문:

2021년 1월 3일

답변:

2021년 1월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by