My goal is pretty simple: I have an arbitrary sized matrix holding only positive real numbers and there will not be anymore than two nonzero elements per column at any time, for example:
b = [1 0 1; 0 1.2 2; 1 3 0];
or
b = [1 2 1 0; 0 1.2 0 0; 0 0 0 3; 1.6 0 4 2.2];
Now what I want is to negate every second nonzero entree of a column. The solution I came up with works, but is probably not the most elegant and/or efficient:
for n=1:numel(b(1,:)) isPositive = 0; for m=1:numel(b(:,n)) if (isPositive == 1 && b(m,n) ~= 0) b(m,n) = b(m,n)*-1; break; end if (abs(b(m,n)) == b(m,n) && b(m,n) ~= 0) isPositive = 1; end endend
I am quite new to MATLAB, so if anybody knows a more elegant solution, perhaps not involving any for loops, please share.
Thanks in advance
Best Answer