What is a more efficient method of increasing non-zero entries by one

1 visualización (últimos 30 días)
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.

Respuesta aceptada

Star Strider
Star Strider el 16 de Mayo de 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
R1 = 1×10
0 0 4 0 0 0 0 0 0 6
ix = (R1>0) & (R1<10)
ix = 1×10 logical array
0 0 1 0 0 0 0 0 0 1
R1(ix) = R1(ix)+1
R1 = 1×10
0 0 5 0 0 0 0 0 0 7
If you want to increment only the 0 entries for example —
R2 = R
R2 = 1×10
0 0 4 0 0 0 0 0 0 6
R2(R2==0) = R2(R2==0) + 1
R2 = 1×10
1 1 4 1 1 1 1 1 1 6
.

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by