Decrementing an Array
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Mustafa
am 11 Jul. 2011
Kommentiert: the cyclist
am 15 Feb. 2016
Hi,
I am new to Matlab and i am trying to decrement a simple array. I want every element to arrives at zero and no negative. The problem is once any element of the array arrives at zero the decrement stops, i have tried to use several combination but nothing works. It goes like this
n=[8 5 9 3 6 11]
if n~=0
n=n-1
end.
As soon as the the value '3' arrives at zero the decrement stops. I have also used "sum" but it didn't work either. For instance while sum~=0, do the decrement but it didn't work either. I know its a simple task but i am stuck.
Akzeptierte Antwort
Weitere Antworten (3)
the cyclist
am 11 Jul. 2011
Edited in response to your comment:
while not(all(n==0))
n = max(0,n-1)
end
Wanted to keep this all in one answer. I have edited my response again, but left the old one. In the code below, I have inserted an if statement that will be entered only when an element of n has just been decremented to zero, as you mentioned you wanted in a comment on andrei's answer.
(I also implemented Jan's simpler syntax for the while loop.)
n0 = [8 5 9 3 6 11];
n = n0;
iter = 0;
while any(n)
iter = iter+1;
n = max(0,n-1)
if any(iter==n0);
% If I am here, it is because one of the original element just reached zero
% Do stuff
end
end
4 Kommentare
Sean de Wolski
am 11 Jul. 2011
n = n-min(n(:));
?
And the way to fix your if statement is to use any as the criterion.
while ~any(n==0)
n = n-1;
end
8 Kommentare
Bheki Ngobe
am 14 Feb. 2016
Hi
I have kind of similar problem but I am using 3x4 array. How should I do it in this situation. In brief I want to apply an formula in each cell and increment to the next one until all cells are updated. Please help
the cyclist
am 15 Feb. 2016
You should probably ask a new question, rather than add a comment to a 4-year-old question.
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!