What is a more efficient method of increasing non-zero entries by one
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Tim David
am 16 Mai 2021
Kommentiert: Star Strider
am 16 Mai 2021
I'm trying to write an array of length 10 where some entries are zero and some are non-zero. I want to increase all the non-zero entries below ten by one and keep all the zero entries as zero. (Code below) The code i have below only covers entry 1 and 3 as an example, it works but it cuts out for all cells when one cell reaches the limit (9) and i need the other cells to carry on. It is also extremely innefficient as it would require me to type out every entry individually and i want to eventually scale this up to 100 cells.
% all non 0 entries will be increased by 1 if below 10.
R = [0, 0, 4, 0, 0, 0, 0, 0, 0, 6];
n = length(R);
m = 1:10;
for i = 1:5
if R(1) < 10
if R(1) ~=0
R(1) = R(1) + 1;
else
R(1) = R(1);
end
end
if R(3) < 10
if R(3) ~= 10
R(3) = R(3) + 1
else
R(3)= R(3)
end
end
end
disp(R(m))
I tried to write a general formula using R(m) instead of R(1), R(2), etc but it increased every entry (even zeroes) by one until one of them reached 9 and then stopped.
So are there any corrections (or new codes entirely) i can make so that all non-zero entries will increase by one each iteration, zeroes remain 0, and each entry relies only on it's own position?
Apologies if this is obvious or poorly explained, and thanks in advance.
0 Kommentare
Akzeptierte Antwort
Star Strider
am 16 Mai 2021
I am not exactly certain what you want to do, however it is straightforward to do this using logical indexing —
R = [0, 0, 4, 0, 0, 0, 0, 0, 0, 6];
R1 = R
ix = (R1>0) & (R1<10)
R1(ix) = R1(ix)+1
If you want to increment only the 0 entries for example —
R2 = R
R2(R2==0) = R2(R2==0) + 1
.
2 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical 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!